Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

In this page you can find the example usage for android.net Uri fromFile.

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Get image from photo library./* w  w  w  . ja  v a 2s. c om*/
 *
 * @param quality           Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
 * @param srcType           The album to get image from.
 * @param returnType        Set the type of image to return.
 * @param encodingType 
 */
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
// TODO: Images from kitkat filechooser not going into crop function
public void getImage(int srcType, int returnType, int encodingType) {
    Intent intent = new Intent();
    String title = GET_PICTURE;
    croppedUri = null;
    if (this.mediaType == PICTURE) {
        intent.setType("image/*");
        if (this.allowEdit) {
            intent.setAction(Intent.ACTION_PICK);
            intent.putExtra("crop", "true");
            if (targetWidth > 0) {
                intent.putExtra("outputX", targetWidth);
            }
            if (targetHeight > 0) {
                intent.putExtra("outputY", targetHeight);
            }
            if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
            }
            File photo = createCaptureFile(encodingType);
            croppedUri = Uri.fromFile(photo);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, croppedUri);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
    } else if (this.mediaType == VIDEO) {
        intent.setType("video/*");
        title = GET_VIDEO;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    } else if (this.mediaType == ALLMEDIA) {
        // I wanted to make the type 'image/*, video/*' but this does not work on all versions
        // of android so I had to go with the wildcard search.
        intent.setType("*/*");
        title = GET_All;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    }
    if (this.activity != null) {
        this.activity.startActivityForResult(Intent.createChooser(intent, new String(title)),
                (srcType + 1) * 16 + returnType + 1);
    }
}

From source file:com.lepin.activity.CarDriverVerify.java

private void getImageByPhoto() {
    path = util.getPath(carId, PhoteName[i], CarDriverVerify.this);
    imageUri = Uri.fromFile(new File(path));
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, CAMERA_RESULT);
}

From source file:com.grass.caishi.cc.activity.RegisterActivity.java

/**
 * ?//  w ww .  j av  a2s.com
 */
public void selectPicFromCamera() {
    // cameraFile = new File(PathUtil.getInstance().getImagePath(),
    // DemoApplication.getInstance().getUserName()
    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(cameraFile)), USERPIC_REQUEST_CODE_CAMERA);
}

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*from   w  w  w.j  a  v a2  s . c o  m*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            //Just because we have a media URI doesn't mean we have a real file, we need to make it
            uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

        }
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(uri.toString());
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits.//from   ww w  .ja v  a2  s . co m
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:info.papdt.blacklight.support.Utility.java

public static void notifyScanPhotos(Context context, String path) {
    Intent i = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri uri = Uri.fromFile(new File(path));
    i.setData(uri);//w  ww  .  j  a  v  a2 s  .  c  om
    context.sendBroadcast(i);
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Brings up the UI to perform crop on passed image URI
 *
 * @param picUri/*  ww  w. j a va  2 s  .co m*/
 */
private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties
        cropIntent.putExtra("crop", "true");
        // indicate output X and Y
        if (targetWidth > 0) {
            cropIntent.putExtra("outputX", targetWidth);
        }
        if (targetHeight > 0) {
            cropIntent.putExtra("outputY", targetHeight);
        }
        if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
        }
        // create new file handle to get full resolution crop
        croppedUri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        cropIntent.putExtra("output", croppedUri);

        // start the activity - we handle returning in onActivityResult

        if (this.cordova != null) {
            this.cordova.startActivityForResult((CordovaPlugin) this, cropIntent, CROP_CAMERA);
        }
    } catch (ActivityNotFoundException anfe) {
        Log.e(LOG_TAG, "Crop operation not supported on this device");
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(picUri.toString());
    }
}

From source file:com.richtodd.android.quiltdesign.app.BlockEditActivity.java

private Uri saveBitmap(RenderStyles renderStyle) throws IOException {

    BlockEditFragment fragment = getBlockEditFragment();
    PaperPiecedBlock block = fragment.getBlock();

    File file = new File(StorageUtility.getPublicFolder(), getCurrentBlockName() + ".png");

    saveBitmap(block, file, renderStyle);

    Uri uri = Uri.fromFile(file);

    return uri;/*from   ww  w  . j a  v a2  s  .  co m*/
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Retorna a URI do arquivo de anexo.//from  w w  w  . java  2 s  .c o  m
 * @return
 */
private Uri getUriArquivo() {
    File f = new File(getCaminhoArquivo(), getFileName());
    return Uri.fromFile(f);
}

From source file:com.dycody.android.idealnote.utils.StorageHelper.java

/**
 * Creates a fiile to be used as attachment.
 *//*from   w  w w .  j  a v a2s.  c o  m*/
public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) {
    String name = FileHelper.getNameFromUri(mContext, uri);
    String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri))
            .toLowerCase(Locale.getDefault());
    File f;
    if (moveSource) {
        f = createNewAttachmentFile(mContext, extension);
        try {
            FileUtils.moveFile(new File(uri.getPath()), f);
        } catch (IOException e) {
            Log.e(Constants.TAG, "Can't move file " + uri.getPath());
        }
    } else {
        f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension);
    }
    Attachment mAttachment = null;
    if (f != null) {
        mAttachment = new Attachment(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri));
        mAttachment.setName(name);
        mAttachment.setSize(f.length());
    }
    return mAttachment;
}