List of usage examples for android.content ContentResolver openInputStream
public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException
From source file:mobisocial.musubi.objects.FileObj.java
public static Obj from(Context context, Uri dataUri) throws IOException { //TODO: is this the proper way to do it? if (dataUri == null) { throw new NullPointerException(); }//from w w w. j a v a 2s . c o m ContentResolver cr = context.getContentResolver(); InputStream in = cr.openInputStream(dataUri); long length = in.available(); String ext; String mimeType; String filename; MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); if ("content".equals(dataUri.getScheme())) { ContentResolver resolver = context.getContentResolver(); mimeType = resolver.getType(dataUri); ext = mimeTypeMap.getExtensionFromMimeType(mimeType); filename = "Musubi-" + sDateFormat.format(new Date()); } else { ext = MimeTypeMap.getFileExtensionFromUrl(dataUri.toString()); mimeType = mimeTypeMap.getMimeTypeFromExtension(ext); filename = Uri.parse(dataUri.toString()).getLastPathSegment(); if (filename == null) { filename = "Musubi-" + sDateFormat.format(new Date()); } } if (mimeType == null || mimeType.isEmpty()) { throw new IOException("Unidentified mime type"); } if (ext == null || ext.isEmpty()) { ext = mimeTypeMap.getExtensionFromMimeType(mimeType); } if (!ext.isEmpty() && !filename.endsWith(ext)) { filename = filename + "." + ext; } if (mimeType.startsWith("video/")) { return VideoObj.from(context, dataUri, mimeType); } else if (mimeType.startsWith("image/")) { return PictureObj.from(context, dataUri, true); } if (length > EMBED_SIZE_LIMIT) { if (length > CORRAL_SIZE_LIMIT) { throw new IOException("file too large for push"); } else { return fromCorral(context, mimeType, filename, length, dataUri); } } else { in = cr.openInputStream(dataUri); return from(mimeType, filename, length, IOUtils.toByteArray(in)); } }
From source file:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java
private static NetworkPackage uriToNetworkPackage(final Context context, final Uri uri) { try {/*from w ww . ja va 2 s .c om*/ ContentResolver cr = context.getContentResolver(); InputStream inputStream = cr.openInputStream(uri); NetworkPackage np = new NetworkPackage(PACKAGE_TYPE_SHARE_REQUEST); long size = -1; if (uri.getScheme().equals("file")) { // file:// is a non media uri, so we cannot query the ContentProvider np.set("filename", uri.getLastPathSegment()); try { size = new File(uri.getPath()).length(); } catch (Exception e) { Log.e("SendFileActivity", "Could not obtain file size"); e.printStackTrace(); } } else { // Probably a content:// uri, so we query the Media content provider Cursor cursor = null; try { String[] proj = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.SIZE, MediaStore.MediaColumns.DISPLAY_NAME }; cursor = cr.query(uri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); cursor.moveToFirst(); String path = cursor.getString(column_index); np.set("filename", Uri.parse(path).getLastPathSegment()); size = new File(path).length(); } catch (Exception unused) { Log.w("SendFileActivity", "Could not resolve media to a file, trying to get info as media"); try { int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME); cursor.moveToFirst(); String name = cursor.getString(column_index); np.set("filename", name); } catch (Exception e) { e.printStackTrace(); Log.e("SendFileActivity", "Could not obtain file name"); } try { int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE); cursor.moveToFirst(); //For some reason this size can differ from the actual file size! size = cursor.getInt(column_index); } catch (Exception e) { Log.e("SendFileActivity", "Could not obtain file size"); e.printStackTrace(); } } finally { try { cursor.close(); } catch (Exception e) { } } } np.setPayload(inputStream, size); return np; } catch (Exception e) { Log.e("SendFileActivity", "Exception sending files"); e.printStackTrace(); return null; } }
From source file:org.sufficientlysecure.keychain.util.FileHelper.java
/** A replacement for ContentResolver.openInputStream() that does not allow * the usage of "file" Uris that point to private files owned by the * application only, *on Lollipop devices*. * * The check will be performed on devices >= Lollipop only, which have the * necessary API to stat filedescriptors. * * @see FileHelperLollipop//w w w . j a v a 2 s. co m */ public static InputStream openInputStreamSafe(ContentResolver resolver, Uri uri) throws FileNotFoundException { // Not supported on Android < 5 if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { return FileHelperLollipop.openInputStreamSafe(resolver, uri); } else { return resolver.openInputStream(uri); } }
From source file:org.kontalk.util.MediaStorage.java
private static void cacheThumbnail(Context context, Uri media, FileOutputStream fout, boolean forNetwork) throws IOException { ContentResolver cr = context.getContentResolver(); InputStream in = cr.openInputStream(media); BitmapFactory.Options options = preloadBitmap(in, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); in.close();/*from w ww. j av a2 s .c om*/ // open again in = cr.openInputStream(media); Bitmap bitmap = BitmapFactory.decodeStream(in, null, options); in.close(); Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); if (thumbnail != bitmap) bitmap.recycle(); Bitmap rotatedThumbnail = bitmapOrientation(context, media, thumbnail); if (rotatedThumbnail != thumbnail) thumbnail.recycle(); // write down to file rotatedThumbnail.compress(forNetwork ? Bitmap.CompressFormat.JPEG : Bitmap.CompressFormat.PNG, forNetwork ? THUMBNAIL_MIME_COMPRESSION : 0, fout); rotatedThumbnail.recycle(); }
From source file:org.kontalk.util.MediaStorage.java
public static File resizeImage(Context context, Uri uri, int maxWidth, int maxHeight, int quality) throws IOException { final int MAX_IMAGE_SIZE = 1200000; // 1.2MP ContentResolver cr = context.getContentResolver(); // compute optimal image scale size int scale = 1; InputStream in = cr.openInputStream(uri); try {// w w w .j a v a 2 s . c o m // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(in, null, o); in.close(); // calculate optimal image scale size while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > MAX_IMAGE_SIZE) scale++; Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight); } catch (IOException e) { Log.d(TAG, "unable to calculate optimal scale size, using original image"); } finally { try { in.close(); } catch (Exception e) { // ignored } } // open image again for the actual scaling Bitmap bitmap = null; try { in = cr.openInputStream(uri); BitmapFactory.Options o = new BitmapFactory.Options(); if (scale > 1) { o.inSampleSize = scale - 1; } bitmap = BitmapFactory.decodeStream(in, null, o); } finally { try { in.close(); } catch (Exception e) { // ignored } } if (bitmap == null) { return null; } float photoW = bitmap.getWidth(); float photoH = bitmap.getHeight(); if (photoW == 0 || photoH == 0) { return null; } float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); int w = (int) (photoW / scaleFactor); int h = (int) (photoH / scaleFactor); if (h == 0 || w == 0) { return null; } Bitmap scaledBitmap = null; try { scaledBitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); } finally { if (scaledBitmap != bitmap) bitmap.recycle(); } // check for rotation data Bitmap rotatedScaledBitmap = bitmapOrientation(context, uri, scaledBitmap); if (rotatedScaledBitmap != scaledBitmap) scaledBitmap.recycle(); final File compressedFile = getOutgoingPictureFile(); FileOutputStream stream = null; try { stream = new FileOutputStream(compressedFile); rotatedScaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream); return compressedFile; } finally { try { stream.close(); } catch (Exception e) { // ignored } rotatedScaledBitmap.recycle(); } }
From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java
/** * Get the MD5 hash of a file as a 32 character hex string. * * @param cr The ContentResolver/*from w ww .j av a 2 s. c om*/ * @param uri The Uri representing the file * @return The MD5 hash of the file or null on failure */ @Nullable public static String getMD5Hash(@NonNull ContentResolver cr, @NonNull Uri uri) { try { final InputStream inputStream = cr.openInputStream(uri); if (inputStream == null) { Log.w(TAG, "Unable to open stream from " + uri.toString()); return null; } try { return getMD5Hash(inputStream); } finally { inputStream.close(); } } catch (FileNotFoundException e) { Log.i(TAG, e.getMessage()); } catch (IOException e) { Log.e(TAG, "Failed to generate MD5 hash", e); } return null; }
From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java
/** * Save a photo from a content Uri to the external storage. * * @param cr The ContentResolver//from w w w . ja va 2 s . c om * @param uri The content Uri * @param file The File to write to or null to create one * @return The file Uri for the new file */ @Nullable private static Uri savePhotoFromUri(@NonNull ContentResolver cr, @NonNull Uri uri, @Nullable File file) { try { if (file == null) { file = getOutputMediaFile(); } final InputStream inputStream = cr.openInputStream(uri); if (inputStream != null) { final OutputStream outputStream = new FileOutputStream(file); try { final byte[] buffer = new byte[8192]; int read; while ((read = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, read); } return Uri.fromFile(file); } finally { inputStream.close(); outputStream.close(); } } } catch (FileNotFoundException e) { Log.w(TAG, "File not found for Uri: " + uri.getPath()); } catch (IOException e) { Log.e(TAG, "Failed to save the photo", e); } return null; }
From source file:com.whiuk.philip.opensmime.PathConverter.java
private static FileInformation handleContentScheme(Context context, Uri uri) { try {// ww w.j ava2 s .c o m ContentResolver contentResolver = context.getContentResolver(); // all fields for one document Cursor cursor = contentResolver.query(uri, null, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { // Note it's called "Display Name". This is // provider-specific, and might not necessarily be the file name. String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); String mimeType = cursor .getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)); InputStream stream = contentResolver.openInputStream(uri); File tmpFile = copyToTempFile(context, stream); return new FileInformation(tmpFile, displayName, mimeType); } } catch (IOException e) { Log.e(OpenSMIME.LOG_TAG, "error in PathConverter.handleContentScheme", e); } return null; }
From source file:de.fau.cs.mad.smile.android.encryption.PathConverter.java
private static FileInformation handleContentScheme(Context context, Uri uri) { try {//from w w w. j ava2s . co m ContentResolver contentResolver = context.getContentResolver(); // all fields for one document Cursor cursor = contentResolver.query(uri, null, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { // Note it's called "Display Name". This is // provider-specific, and might not necessarily be the file name. String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); String mimeType = cursor .getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)); InputStream stream = contentResolver.openInputStream(uri); File tmpFile = copyToTempFile(context, stream); return new FileInformation(tmpFile, displayName, mimeType); } } catch (IOException e) { Log.e(SMileCrypto.LOG_TAG, "error in PathConverter.handleContentScheme", e); } return null; }
From source file:com.android.dialer.lookup.yellowpages.YellowPagesReverseLookup.java
/** * Lookup image/*from ww w . j a v a 2s.c om*/ * * @param context The application context * @param uri The image URI */ public Bitmap lookupImage(Context context, Uri uri) { if (uri == null) { throw new NullPointerException("URI is null"); } Log.e(TAG, "Fetching " + uri); String scheme = uri.getScheme(); if (scheme.startsWith("http")) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(uri.toString()); try { HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); byte[] responseBytes = out.toByteArray(); if (responseCode == HttpStatus.SC_OK) { Bitmap bmp = BitmapFactory.decodeByteArray(responseBytes, 0, responseBytes.length); return bmp; } } catch (IOException e) { Log.e(TAG, "Failed to retrieve image", e); } } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) { try { ContentResolver cr = context.getContentResolver(); Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri)); return bmp; } catch (FileNotFoundException e) { Log.e(TAG, "Failed to retrieve image", e); } } return null; }