Example usage for android.content ContentResolver openInputStream

List of usage examples for android.content ContentResolver openInputStream

Introduction

In this page you can find the example usage for android.content ContentResolver openInputStream.

Prototype

public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Open a stream on to the content associated with a content URI.

Usage

From source file:Main.java

public static Bitmap loadSizeLimitedBitmapFromUri(Uri imageUri, ContentResolver contentResolver) {
    try {/*from w w w .  j a  v  a 2  s  . com*/
        // Load the image into InputStream.
        InputStream imageInputStream = contentResolver.openInputStream(imageUri);

        // For saving memory, only decode the image meta and get the side length.
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Rect outPadding = new Rect();
        BitmapFactory.decodeStream(imageInputStream, outPadding, options);

        // Calculate shrink rate when loading the image into memory.
        int maxSideLength = options.outWidth > options.outHeight ? options.outWidth : options.outHeight;
        options.inSampleSize = 1;
        options.inSampleSize = calculateSampleSize(maxSideLength, IMAGE_MAX_SIDE_LENGTH);
        options.inJustDecodeBounds = false;
        imageInputStream.close();

        // Load the bitmap and resize it to the expected size length
        imageInputStream = contentResolver.openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream, outPadding, options);
        maxSideLength = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        double ratio = IMAGE_MAX_SIDE_LENGTH / (double) maxSideLength;
        if (ratio < 1) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * ratio),
                    (int) (bitmap.getHeight() * ratio), false);
        }

        return rotateBitmap(bitmap, getImageRotationAngle(imageUri, contentResolver));
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static Bitmap loadSizeLimitedBitmapFromUri(Uri imageUri, ContentResolver contentResolver) {
    try {//ww  w .ja  va  2  s  . c om
        // Load the image into InputStream.
        InputStream imageInputStream = contentResolver.openInputStream(imageUri);

        // For saving memory, only decode the image meta and get the side length.
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Rect outPadding = new Rect();
        BitmapFactory.decodeStream(imageInputStream, outPadding, options);

        // Calculate shrink rate when loading the image into memory.
        int maxSideLength = options.outWidth > options.outHeight ? options.outWidth : options.outHeight;
        options.inSampleSize = 1;
        options.inSampleSize = calculateSampleSize(maxSideLength, IMAGE_MAX_SIDE_LENGTH);
        options.inJustDecodeBounds = false;
        if (imageInputStream != null) {
            imageInputStream.close();
        }

        // Load the bitmap and resize it to the expected size length
        imageInputStream = contentResolver.openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream, outPadding, options);
        maxSideLength = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
        double ratio = IMAGE_MAX_SIDE_LENGTH / (double) maxSideLength;
        if (ratio < 1) {
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * ratio),
                    (int) (bitmap.getHeight() * ratio), false);
        }

        return rotateBitmap(bitmap, getImageRotationAngle(imageUri, contentResolver));
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

/**
 * A safer decodeStream method/*from  w  ww .ja v  a  2s.c o  m*/
 * rather than the one of {@link BitmapFactory} which will be easy to get OutOfMemory Exception
 * while loading a big image file.
 * 
 * @param uri
 * @param width
 * @param height
 * @return
 * @throws FileNotFoundException
 */
protected static Bitmap safeDecodeStream(Context context, Uri uri, int width, int height)
        throws FileNotFoundException {
    int scale = 1;
    // Decode image size without loading all data into memory  
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    android.content.ContentResolver resolver = context.getContentResolver();
    try {

        BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024), null,
                options);
        if (width > 0 || height > 0) {
            options.inJustDecodeBounds = true;
            int w = options.outWidth;
            int h = options.outHeight;
            while (true) {
                if ((width > 0 && w / 2 < width) || (height > 0 && h / 2 < height)) {
                    break;
                }
                w /= 2;
                h /= 2;
                scale *= 2;
            }
        }
        // Decode with inSampleSize option  
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        return BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024),
                null, options);
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
    }
    return null;
}

From source file:Main.java

/**
 * Read bytes.//from   w ww . j  ava  2s  . c  o  m
 *
 * @param uri      the uri
 * @param resolver the resolver
 * @return the byte[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail) throws IOException {
    // this dynamically extends to take the bytes you read
    InputStream inputStream = resolver.openInputStream(uri);
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

    if (!thumbnail) {
        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the
        // byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
    } else {
        Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
        int thumb_width = imageBitmap.getWidth() / 2;
        int thumb_height = imageBitmap.getHeight() / 2;
        if (thumb_width > THUMBNAIL_SIZE) {
            thumb_width = THUMBNAIL_SIZE;
        }
        if (thumb_width == THUMBNAIL_SIZE) {
            thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE) / (imageBitmap.getWidth() / 2);
        }
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
    }
    // and then we can return your byte array.
    return byteBuffer.toByteArray();
}

From source file:Main.java

/**
 * Returns a mutable bitmap from a uri.//ww w .  j a va 2 s. co  m
 *
 * @param uri Uri to the file
 * @return A mutable copy of the decoded {@link android.graphics.Bitmap}; null if failed.
 * @throws java.io.IOException if unable to make it mutable
 */
public static Bitmap decodeUri(final ContentResolver resolver, final Uri uri) throws IOException {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = false;
    opt.inMutable = true;
    return BitmapFactory.decodeStream(resolver.openInputStream(uri), null, opt);
}

From source file:ee.ria.DigiDoc.util.FileUtils.java

private static File writeUriDataToDirectory(File directory, Uri uri, String filename,
        ContentResolver contentResolver) {
    File destination = new File(directory, filename);
    try {//from   ww w . j  a  v  a  2s.com
        InputStream inputStream = contentResolver.openInputStream(uri);
        return writeToFile(destination, inputStream);
    } catch (Exception e) {
        Timber.e(e, "failed to cache URI data");
        throw new FailedToCacheUriDataException(e);
    }
}

From source file:Main.java

public static Bitmap load(ContentResolver contentResolver, Uri uri, int minSideLen, int maxSize) {

    Bitmap result = EMPTY_BITMAP;//from ww w .j  a v a 2 s. c o m
    try {
        Options opts = new Options();
        opts.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(contentResolver.openInputStream(uri), null, opts);

        result = load(contentResolver.openInputStream(uri), computeSampleSize(opts, minSideLen, maxSize));

        if (isMediaUri(uri) && result != null && result != EMPTY_BITMAP) {
            result = rotateMediaImage(contentResolver, uri, result);
        }

    } catch (OutOfMemoryError e) {
        Log.e("LoadImage", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("LoadImage", e.getMessage(), e);
    }
    if (result == null) {
        result = EMPTY_BITMAP;
    }
    return result;
}

From source file:org.jared.synodroid.ds.utils.Utils.java

public static Uri moveToStorage(Activity a, Uri uri) {
    ContentResolver cr = a.getContentResolver();
    try {/*  w w w  . j  a  va  2 s . c om*/
        InputStream is = cr.openInputStream(uri);

        File path = Environment.getExternalStorageDirectory();
        path = new File(path, "Android/data/org.jared.synodroid.ds/cache/");
        path.mkdirs();

        String fname = getContentName(cr, uri);
        File file = null;
        if (fname != null) {
            file = new File(path, fname);
        } else {
            file = new File(path, "attachment.att");
        }

        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

        return uri = Uri.fromFile(file);
    } catch (FileNotFoundException e) {
        // do nothing
    } catch (IOException e) {
        // do nothing
    }

    return null;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public static DbObject from(Context context, Uri imageUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*  w w w  .  j  av a  2  s . c  o  m*/
    BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int targetSize = 200;
    int xScale = (options.outWidth + targetSize - 1) / targetSize;
    int yScale = (options.outHeight + targetSize - 1) / targetSize;

    int scale = xScale < yScale ? xScale : yScale;
    //uncomment this to get faster power of two scaling
    //for(int i = 0; i < 32; ++i) {
    //   int mushed = scale & ~(1 << i);
    //   if(mushed != 0)
    //      scale = mushed;
    //}

    options.inJustDecodeBounds = false;
    options.inSampleSize = scale;

    Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int width = sourceBitmap.getWidth();
    int height = sourceBitmap.getHeight();
    int cropSize = Math.min(width, height);

    float scaleSize = ((float) targetSize) / cropSize;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    float rotation = PhotoTaker.rotationForImage(context, imageUri);
    if (rotation != 0f) {
        matrix.preRotate(rotation);
    }

    Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    sourceBitmap.recycle();
    sourceBitmap = null;
    resizedBitmap.recycle();
    resizedBitmap = null;
    System.gc(); // TODO: gross.

    JSONObject base = new JSONObject();
    if (ContentCorral.CONTENT_CORRAL_ENABLED) {
        try {
            String type = cr.getType(imageUri);
            if (type == null) {
                type = "image/jpeg";
            }
            base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString());
            base.put(CorralClient.OBJ_MIME_TYPE, type);
            String localIp = ContentCorral.getLocalIpAddress();
            if (localIp != null) {
                base.put(Contact.ATTR_LAN_IP, localIp);
            }
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }
    return from(base, data);
}

From source file:org.sufficientlysecure.keychain.util.FileHelper.java

public static void copyUriData(Context context, Uri fromUri, Uri toUri) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {/*from w ww .  j a va 2s .  c  om*/
        ContentResolver resolver = context.getContentResolver();
        bis = new BufferedInputStream(resolver.openInputStream(fromUri));
        bos = new BufferedOutputStream(resolver.openOutputStream(toUri));
        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            // ignore, it's just stream closin'
        }
    }
}