Example usage for android.graphics BitmapFactory decodeByteArray

List of usage examples for android.graphics BitmapFactory decodeByteArray

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeByteArray.

Prototype

public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) 

Source Link

Document

Decode an immutable bitmap from the specified byte array.

Usage

From source file:com.daiv.android.twitter.services.SendTweet.java

public Bitmap getBitmapToSend(Uri uri, Context context) throws IOException {
    InputStream input = context.getContentResolver().openInputStream(uri);
    int reqWidth = 750;
    int reqHeight = 750;

    byte[] byteArr = new byte[0];
    byte[] buffer = new byte[1024];
    int len;/*from w  w  w .  j  a  v  a2  s  . c  om*/
    int count = 0;

    try {
        while ((len = input.read(buffer)) > -1) {
            if (len != 0) {
                if (count + len > byteArr.length) {
                    byte[] newbuf = new byte[(count + len) * 2];
                    System.arraycopy(byteArr, 0, newbuf, 0, count);
                    byteArr = newbuf;
                }

                System.arraycopy(buffer, 0, byteArr, count, len);
                count += len;
            }
        }

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Bitmap b = BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        return rotateBitmap(b, orientation);

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

        return null;
    }
}

From source file:com.yk.notification.util.BitmapUtil.java

/**
 * ??bitmap//w  ww  .  j  a  v a  2  s . c  om
 * 
 * @param data
 *            Bitmapbyte
 * @param offset
 *            imagebyte?
 * @param length
 *            the number of bytes, offset
 * @param reqWidth
 *            
 * @param reqHeight
 *            
 */
public static Bitmap getBitmapFromByteArray(byte[] data, int offset, int length, int reqWidth, int reqHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, offset, length, options);
    options = calculateInSampleSize(options, reqWidth, reqHeight);
    return BitmapFactory.decodeByteArray(data, offset, length, options);
}

From source file:com.life.wuhan.util.ImageDownloader.java

private Bitmap downloadBitmap(final String imageUrl) {

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = new DefaultHttpClient();
    // ??/*from   w w  w  .j  ava  2s  . c  o  m*/
    if (NetworkUtil.getNetworkType(mContext) == NetworkUtil.APN_CMWAP) {
        HttpHost proxy = new HttpHost(NetworkUtil.getHostIp(), NetworkUtil.getHostPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    final HttpGet getRequest = new HttpGet(imageUrl);
    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            final byte[] respBytes = EntityUtils.toByteArray(entity);
            writeImageFile(imageUrl, entity, respBytes);
            // Decode the bytes and return the bitmap.
            return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, null);

        }
    } catch (IOException e) {
        getRequest.abort();
    } catch (OutOfMemoryError e) {
        clearCache();
        System.gc();
    } catch (IllegalStateException e) {
        getRequest.abort();
    } catch (Exception e) {
        getRequest.abort();
    } finally {
    }
    return null;
}

From source file:se.dw.okhttpwrapper.ImageRequest.java

private Bitmap downloadBitmap(String url) {
    OkHttpClient client = OkHttpWrapper.getClient();

    if (client == null) {
        Log.w(LOG_TAG, "OkHttpWrapper not initialized, " + url);
        return null;
    }/*from w  w  w  .j ava2 s  .  c o  m*/

    InputStream in = null;
    HttpURLConnection connection = null;
    try {

        connection = client.open(new URL(url));

        /*
         * http://stackoverflow.com/questions/10550349/retriving-image-from-server-to-android-app
         * Reading directly from stream sometimes BitmapFactory returns null.
         */

        in = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(in, 8190);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        byte[] imageData = baf.toByteArray();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);

        int reqWidth = maxImageWidth;
        int reqHeight = maxImageHeight;

        options.inJustDecodeBounds = false;

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);

        return bitmap;

    } catch (IOException e) {
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url + "\n" + e.toString());
    } catch (IllegalStateException e) {
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if (in != null) {
        }
        if (connection != null) {
        }
    }

    return null;
}

From source file:biz.varkon.shelvesom.util.ImageUtilities.java

/**
 * Loads an image from the specified URL with the specified cookie.
 * /*from   www.ja va 2 s  .  c  om*/
 * @param url
 *            The URL of the image to load.
 * @param cookie
 *            The cookie to use to load the image.
 * 
 * @return The image at the specified URL or null if an error occured.
 */
public static ExpiringBitmap load(String url, String cookie) {
    ExpiringBitmap expiring = new ExpiringBitmap();

    final HttpGet get = new HttpGet(url);
    if (cookie != null)
        get.setHeader("cookie", cookie);

    HttpEntity entity = null;
    try {
        final HttpResponse response = HttpManager.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            setLastModified(expiring, response);

            entity = response.getEntity();

            InputStream in = null;
            OutputStream out = null;

            try {
                in = entity.getContent();

                if (FLAG_DECODE_BITMAP_WITH_SKIA) {
                    expiring.bitmap = BitmapFactory.decodeStream(in);
                } else {
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    out = new BufferedOutputStream(dataStream, IOUtilities.IO_BUFFER_SIZE);
                    IOUtilities.copy(in, out);
                    out.flush();

                    final byte[] data = dataStream.toByteArray();

                    final double ratio = getScale(in);

                    final BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
                    bitmapOptions.inDither = true;
                    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;

                    expiring.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, bitmapOptions);
                }
            } catch (IOException e) {
                android.util.Log.e(LOG_TAG, "Could not load image from " + url, e);
            } catch (OutOfMemoryError oom) {
                expiring.bitmap = null;
            } finally {
                IOUtilities.closeStream(in);
                IOUtilities.closeStream(out);
            }
        }
    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not load image from " + url, e);
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
                android.util.Log.e(LOG_TAG, "Could not load image from " + url, e);
            }
        }
    }

    return expiring;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

static Bitmap getBitmap(Cursor cursor, int columnIndex, Bitmap inBitmap) {
    byte[] data = cursor.getBlob(columnIndex);
    if (data == null) {
        return null;
    }//from w  w w  .  j  av a 2 s. co  m
    Options opts = sOptions.get();
    opts.inBitmap = inBitmap;
    opts.inSampleSize = 1;
    opts.inScaled = false;
    try {
        return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
    } catch (IllegalArgumentException ex) {
        // Failed to re-use bitmap, create a new one
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }
}

From source file:com.silentcircle.contacts.list.ShortcutIntentBuilder.java

private Drawable getPhotoDrawable(byte[] bitmapData, String displayName, String lookupKey) {
    if (bitmapData != null) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length, null);
        return new BitmapDrawable(mContext.getResources(), bitmap);
    } else {//from w ww  . j  a  v  a  2  s. c om
        return ContactPhotoManagerNew.getDefaultAvatarDrawableForContact(mContext.getResources(), false,
                new DefaultImageRequest(displayName, lookupKey, false));
    }
}

From source file:com.android.contacts.common.list.ShortcutIntentBuilder.java

private Drawable getPhotoDrawable(byte[] bitmapData, String displayName, String lookupKey) {
    if (bitmapData != null) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length, null);
        return new BitmapDrawable(mContext.getResources(), bitmap);
    } else {/* www  .  j  a v a  2 s.  co m*/
        return ContactPhotoManager.getDefaultAvatarDrawableForContact(mContext.getResources(), false,
                new DefaultImageRequest(displayName, lookupKey, false));
    }
}

From source file:com.bamobile.fdtks.util.Tools.java

public static Bitmap getBitmapFromURL(Context context, String imageUrl, int width, int height) {
    if (imageUrl != null && imageUrl.length() > 0) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(imageUrl.replace(" ", "%20"));
        try {/*from   www.  ja  v  a  2s.  c o m*/
            HttpResponse response = client.execute(get);
            byte[] content = EntityUtils.toByteArray(response.getEntity());
            //get the dimensions of the image
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(content, 0, content.length, opts);

            // get the image and scale it appropriately
            opts.inJustDecodeBounds = false;
            opts.inSampleSize = Math.max(opts.outWidth / width, opts.outHeight / height);

            Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length, opts);
            if (bitmap == null) {
                return null;
            }

            int scaledWidth = bitmap.getWidth();
            int scaledHeight = bitmap.getHeight();

            if (scaledWidth < scaledHeight) {
                float scale = width / (float) scaledWidth;

                scaledWidth = width;
                scaledHeight = (int) Math.ceil(scaledHeight * scale);
                if (scaledHeight < height) {
                    scale = height / (float) scaledHeight;

                    scaledHeight = height;
                    scaledWidth = (int) Math.ceil(scaledWidth * scale);
                }
            } else {
                float scale = height / (float) scaledHeight;

                scaledHeight = height;
                scaledWidth = (int) Math.ceil(scaledWidth * scale);

                if (scaledWidth < width) {
                    scale = width / (float) scaledWidth;

                    scaledWidth = width;
                    scaledHeight = (int) Math.ceil(scaledHeight * scale);
                }
            }

            Bitmap bmp = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false);

            bitmap.recycle();
            bitmap = null;

            return bmp;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:free.yhc.feeder.model.Utils.java

/**
 * Decode image from file path(String) or raw data (byte[]).
 * @param image/*from   ww  w . ja  va2 s  .  c  o  m*/
 *   Two types are supported.
 *   String for file path / byte[] for raw image data.
 * @param opt
 * @return
 */
private static Bitmap decodeImageRaw(Object image, BitmapFactory.Options opt) {
    if (image instanceof String) {
        return BitmapFactory.decodeFile((String) image, opt);
    } else if (image instanceof byte[]) {
        byte[] data = (byte[]) image;
        return BitmapFactory.decodeByteArray(data, 0, data.length, opt);
    }
    eAssert(false);
    return null;
}