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.support.android.designlibdemo.activities.CampaignDetailActivity.java

public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;//  w  w  w  .j av  a  2s  .co  m
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }

    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;

}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private void download(String urlstr, String marketDa) {
    try {//  w w w  .j  a v a2s  .  co  m
        final HttpGet request = new HttpGet(urlstr);
        request.addHeader("User-Agent", "Android-Market/2");
        request.addHeader("Cookie", "MarketDA=" + marketDa);

        final HttpResponse response = mClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            updateMessage(R.string.error_download, response.getStatusLine().getReasonPhrase());
            return;
        }

        final File file = new File(Environment.getExternalStorageDirectory(), PACKAGE_NAME + ".apk");
        if (file.exists()) {
            file.delete();
        }
        final FileOutputStream out = new FileOutputStream(file);
        final InputStream in = response.getEntity().getContent();
        long total = response.getEntity().getContentLength();
        long len = total;
        try {
            final byte[] buf = new byte[BUFSIZE];
            while (len > 0) {
                int rsz = in.read(buf);
                if (rsz < 0) {
                    break;
                }
                out.write(buf, 0, rsz);
                len -= rsz;
                updateProgress((int) (100 * (total - len) / total));
            }
            if (len != 0) {
                updateMessage(R.string.error_download, "Insufficient Response");
                return;
            }

            updateMessage(R.string.install_package, null);
            final Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(intent);
            finish();
        } finally {
            in.close();
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        updateMessage(R.string.error_download, e.toString());
    }
}

From source file:com.poomoo.edao.activity.UploadPicsActivity.java

private void getPicByCamera() {
    Intent intent1 = new Intent("android.media.action.IMAGE_CAPTURE");
    intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(image_capture_path)));
    startActivityForResult(intent1, PHOTOHRAPH);
}

From source file:com.example.zf_android.activity.MerchantEdit.java

private void show2Dialog(int type) {

    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this);
    final String[] items = getResources().getStringArray(R.array.apply_detail_upload);

    MerchantEdit.this.type = type;

    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override/*from  w w w.  j a va  2 s.c o  m*/
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {

            case 0: {

                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                break;
            }
            case 1: {
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    if (!outDir.exists()) {
                        outDir.mkdirs();
                    }
                    File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                    photoPath = outFile.getAbsolutePath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                } else {
                    CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_no_sdcard));
                }
                break;
            }
            }
        }
    });

    builder.show();
}

From source file:com.remobile.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 .  jav a2s  .  c  om
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();
    String sourcePath;
    try {
        if (allowEdit && croppedUri != null) {
            sourcePath = FileHelper.stripFileProtocol(croppedUri.toString());
        } else {
            sourcePath = getTempDirectoryPath() + "/.Pic.jpg";
        }

        //We don't support PNG, so let's not pretend we do
        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) {
        if (croppedUri != null) {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(croppedUri.toString()));
        } else {
            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) {
        uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));

        if (this.saveToPhotoAlbum) {
            //Create a URI on the filesystem so that we can write the file.
            uri = Uri.fromFile(new File(getPicutresPath()));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

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

        // 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;
                exifPath = uri.getPath();
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

            //Broadcast change to File System on MediaStore
            if (this.saveToPhotoAlbum) {
                refreshGallery(uri);
            }

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

        }
    } else {
        throw new IllegalStateException();
    }

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

From source file:es.upv.riromu.arbre.main.MainActivity.java

/******************************************/
public void cropImage(View view) {
    Intent intent = new Intent(this, CropImageActivity.class);
    ImageView imv = (ImageView) findViewById(R.id.image_intro);
    try {/*w ww .j av a2  s .c om*/
        image = ((BitmapDrawable) imv.getDrawable()).getBitmap();
        croppedimage_uri = Uri.fromFile(createImageFile());

    } catch (IOException e) {
        e.printStackTrace();
    }

    //Convert to byte array
    if (getImageUri() != null) {
        intent.putExtra("image", getImageUri().toString());//tostring for passing it
        intent.putExtra("imageSave", croppedimage_uri.toString());//tostring for passing it
        intent.putExtra(RETURN_DATA, true);
        //     intent.putExtra(RETURN_DATA_AS_BITMAP, true);
    } else {
        intent.putExtra("image", "default");
    }
    intent.putExtra(CropImageActivity.SCALE, true);
    intent.putExtra(CropImageActivity.ASPECT_X, 3);
    intent.putExtra(CropImageActivity.ASPECT_Y, 2);
    try {

        startActivityForResult(intent, CROP_IMAGE);
    } catch (Exception e) {
        Log.e(TAG, "Error calling crop" + e.getMessage());
    }
}

From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Send an Intent requesting for an activity to display the content.
 * //from w  ww . j a v  a2s  .  c om
 * @param file
 * @param ref
 */
protected void viewContent(File file, NodeRef ref) {
    Context context = getContext();

    // Ask for viewer
    Uri uri = Uri.fromFile(file);
    Intent viewIntent = new Intent(Intent.ACTION_VIEW);
    viewIntent.setDataAndType(uri, ref.getContentType());
    try {
        context.startActivity(viewIntent);
    } catch (ActivityNotFoundException e) {
        deleteContent(file);
        String text = "No viewer found for " + ref.getContentType();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;/*from w  ww.  jav  a  2 s .c o  m*/

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.abc.driver.TruckActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CellSiteConstants.TAKE_PICTURE || requestCode == CellSiteConstants.PICK_PICTURE) {

        Uri uri = null;/*from www . ja v  a2  s . co  m*/
        if (requestCode == CellSiteConstants.TAKE_PICTURE) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_PICTURE) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().getMyTruck().setLicenseImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        // doCrop();

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, IMAGE_WIDTH, IMAGE_HEIGHT, false);

        mTLPiv.setImageBitmap(scaledBmp);
        isPortraitChanged = true;
        Log.d(TAG, "onActivityResult PICK_PICTURE");
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), "" + app.getUser().getMyTruck().getTruckId(),
                Utils.bitmap2String(scaledBmp), CellSiteConstants.UPDATE_TRUCK_LICENSE_URL);

    } else if (requestCode == CellSiteConstants.CROP_PICTURE) {
        Log.d(TAG, "crop picture");
        // processFile();

        if (data != null) {
            Bundle extras = data.getExtras();
            Bitmap photo = extras.getParcelable("data");

            trcukLicenseBmp = photo;
            mTLPiv.setImageBitmap(trcukLicenseBmp);
            mUpdateImageTask = new UpdateImageTask();
            mUpdateImageTask.execute("" + app.getUser().getId(), "" + app.getUser().getMyTruck().getTruckId(),
                    Utils.bitmap2String(trcukLicenseBmp), CellSiteConstants.UPDATE_DRIVER_LICENSE_URL);

            isPortraitChanged = true;
        }
    } else if (requestCode == CellSiteConstants.TAKE_PICTURE2
            || requestCode == CellSiteConstants.PICK_PICTURE2) {

        Uri uri = null;
        if (requestCode == CellSiteConstants.TAKE_PICTURE2) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_PICTURE2) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().getMyTruck().setPhotoImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        // doCrop();

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, IMAGE_WIDTH, IMAGE_HEIGHT, false);

        mTPiv.setImageBitmap(scaledBmp);
        // s isChanged = true;
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), "" + app.getUser().getMyTruck().getTruckId(),
                Utils.bitmap2String(scaledBmp), CellSiteConstants.UPDATE_TRUCK_PHOTO_URL);

    } else if (requestCode == CellSiteConstants.UPDATE_TRUCK_MOBILE_REQUSET) {
        Log.d(TAG, "mobile changed");
        if (app.getUser().getMyTruck().getMobileNum() == null) {
            mTMtv.setText(app.getUser().getMobileNum());
            app.getUser().getMyTruck().setMobileNum(app.getUser().getMobileNum());

        } else {
            mTMtv.setText(app.getUser().getMyTruck().getMobileNum());
        }
    }
}

From source file:com.cordova.photo.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  ww  . ja  va 2s  . 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();
        } else if (this.encodingType == PNG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.png");
            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) {
        if (imageUri != null)
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            if (intent != null && intent.getExtras() != null) {
                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();
            try {
                //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.activity)));
            } catch (NullPointerException e) {
                uri = null;
            }
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

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

        // 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.activity.getContentResolver().openOutputStream(uri);
            bitmap.compress(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.activity);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }
            if (this.allowEdit) {
                performCrop(uri);
            } else {
                // Send Uri back to JavaScript for viewing image
                this.callbackContext.success(uri.toString());
            }
        }
    } else {
        throw new IllegalStateException();
    }

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