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.android.contacts.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 {//  w ww . j a va  2  s.c o  m
        final DefaultImageRequest request = new DefaultImageRequest(displayName, lookupKey, false);
        if (BuildCompat.isAtLeastO()) {
            // On O, scale the image down to add the padding needed by AdaptiveIcons.
            request.scale = LetterTileDrawable.getAdaptiveIconScale();
        }
        return ContactPhotoManager.getDefaultAvatarDrawableForContact(mContext.getResources(), false, request);
    }
}

From source file:com.gmail.jiangyang5157.cardboard.net.DescriptionRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *//*from   w  ww.  j ava 2 s .co  m*/
private Response<Object> doBitmapParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap;
    if (mMaxWidth == 0 && mMaxHeight == 0) {
        decodeOptions.inPreferredConfig = mDecodeConfig;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }

    if (bitmap == null) {
        return Response.error(new ParseError(response));
    } else {
        return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
    }
}

From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java

public static Bitmap getBitmapFromByteArray(byte[] byteArray, int maxSize) {
    Bitmap bitmap = null;//from   w  w w . j av  a2  s  .c om
    try {
        try {

            int sampleFactor = getSampleFactor(byteArray, maxSize);
            BitmapFactory.Options resample = new BitmapFactory.Options();
            resample.inSampleSize = sampleFactor;
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, resample);
        } catch (Error e) {

            // Avoid that heap has to be grown for the BitmapFactory,
            // as this would lead to an out of memory error
            int[] dummyArray = new int[byteArray.length];
            // Avoid being eliminated by optimization of compiler
            if (dummyArray != null) {
                dummyArray = null;
                System.gc();
            }
            Log.w("BitmapFactory", e);
        }
        if (bitmap == null) {
            try {
                int sampleFactor = getSampleFactor(byteArray, maxSize);
                BitmapFactory.Options resample = new BitmapFactory.Options();
                resample.inSampleSize = sampleFactor;
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, resample);
            } catch (Error e) {
                System.gc();
                Log.w("BitmapFactory", e);
            }
        }
    } catch (Throwable e) {
        Log.w("Bitmap", e);
    }
    return bitmap;
}

From source file:edu.cloud.iot.reception.ocr.FaceRecognitionActivity.java

private Bitmap ShrinkBitmap(byte[] imgByte, int width, int height) {

    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length, bmpFactoryOptions);

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);

    if (heightRatio > 1 || widthRatio > 1) {
        if (heightRatio > widthRatio) {
            bmpFactoryOptions.inSampleSize = heightRatio;
        } else {/*  w  w  w.  jav  a  2 s.c  o  m*/
            bmpFactoryOptions.inSampleSize = widthRatio;
        }
    }
    Log.i("EDebug::ShrinkBitmap() - ", "bmpFactoryOptions.inSampleSize=" + bmpFactoryOptions.inSampleSize);

    bmpFactoryOptions.inJustDecodeBounds = false;
    // bmpFactoryOptions.inSampleSize = 16;
    bitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length, bmpFactoryOptions);
    return bitmap;
}

From source file:org.csware.ee.utils.Tools.java

/**
 * ?/*from w w  w. j a va  2  s .  c o  m*/
 * @param imgUrl   
 * @return     Bitmap
 * @throws Exception
 */
public static Bitmap getBitmapFromUrl(String imgUrl) {
    //         Log.i("[value]", "Tools getBitmapFromUrl" + imgUrl);
    byte[] buffer = getByteArray(imgUrl);
    return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, null);
}

From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java

/**
 * If necessary, decodes bytes stored in the holder to Bitmap. As long as
 * the bitmap is held either by {@link #mBitmapCache} or by a soft reference
 * in the holder, it will not be necessary to decode the bitmap.
 *//*from   w  ww.j a va 2 s.  co m*/
private static void inflateBitmap(BitmapHolder holder) {
    byte[] bytes = holder.bytes;
    if (bytes == null || bytes.length == 0) {
        return;
    }

    // Check the soft reference. If will be retained if the bitmap is also
    // in the LRU cache, so we don't need to check the LRU cache explicitly.
    if (holder.bitmapRef != null) {
        holder.bitmap = holder.bitmapRef.get();
        if (holder.bitmap != null) {
            return;
        }
    }

    try {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
        holder.bitmap = bitmap;
        holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
    } catch (OutOfMemoryError e) {
        // Do nothing - the photo will appear to be missing
    }
}

From source file:com.almalence.googsharing.Thumbnail.java

public static Thumbnail createThumbnail(byte[] jpeg, int orientation, int inSampleSize, Uri uri) {
    // Create the thumbnail.
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = inSampleSize;
    Bitmap bitmap = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, options);
    return createThumbnail(uri, bitmap, null, orientation);
}

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

public static Bitmap decodeByteArray(byte[] data, int index, int length) {
    try {//from  w ww . jav a  2s . c om
        WindowManager wm = (WindowManager) SplashActivity.getInstance()
                .getSystemService(Context.WINDOW_SERVICE);
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        o.inInputShareable = true;
        o.inPurgeable = true;
        o.inDither = false;
        BitmapFactory.decodeByteArray(data, index, length, o);

        //The new size we want to scale to
        final int IMAGE_MAX_SIZE = wm.getDefaultDisplay().getWidth();

        //Find the correct scale value. It should be the power of 2.
        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.ceil(
                    Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        o.inSampleSize = scale;
        o.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(data, index, length, o);
    } catch (Exception e) {
        Log.e("Tools.decodeByteArray", e.getMessage(), e);
    }
    return null;
}

From source file:org.csware.ee.utils.Tools.java

public static Bitmap getBitmapFromUrl(String imgUrl, String cookie) {
    //         Log.i("[value]", "Tools getBitmapFromUrl" + imgUrl);
    byte[] buffer = getByteArray(imgUrl, cookie);
    //        Log.i("bufff", buffer.length + "...");
    return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, null);
}

From source file:com.fastbootmobile.encore.art.AlbumArtCache.java

private boolean getAlbumArtImpl(final Resources res, final Album album, final Artist hintArtist,
        final IAlbumArtCacheListener listener, final BoundEntity listenerRef) throws RemoteException {
    // Try to get the art from the provider first
    final ProviderIdentifier id = album.getProvider();
    final IMusicProvider binder = safeGetBinder(id);

    boolean providerprovides = false;
    boolean result = false;

    if (binder != null) {
        providerprovides = result = binder.getAlbumArt(album, new IArtCallback.Stub() {
            @Override/*from  w  w w. jav a 2 s.co m*/
            public void onArtLoaded(final Bitmap bitmap) throws RemoteException {
                new Thread() {
                    public void run() {
                        if (bitmap != null) {
                            RecyclingBitmapDrawable rcb = ImageCache.getDefault().put(res,
                                    getEntityArtKey(album), bitmap);
                            listener.onArtLoaded(album, rcb);
                        } else {
                            listener.onArtLoaded(album, null);
                        }
                    }
                }.start();
            }
        });
    }

    if (!providerprovides) {
        String url = null;
        final String artistRef = (album.getSongsCount() > 0 ? Utils.getMainArtist(album) : null);
        final String albumName = album.getName();
        String artistName = (hintArtist != null ? hintArtist.getName() : null);

        // If we have the artist, bias the search with it
        if (artistName == null && artistRef != null) {
            Artist artist = ProviderAggregator.getDefault().retrieveArtist(artistRef, id);
            if (artist != null && artist.getName() != null && !artist.getName().isEmpty()) {
                artistName = artist.getName();
            }
        }

        if (artistName == null && albumName == null) {
            // No artist name neither album name, bail out
            return false;
        }

        // Try to get from Google Images
        try {
            if (artistName != null && albumName != null) {
                url = GoogleImagesClient.getImageUrl("album " + artistName + " " + albumName);
            } else if (artistName == null) {
                url = GoogleImagesClient.getImageUrl("album " + albumName);
            } else {
                url = GoogleImagesClient.getImageUrl("album from " + artistName);
            }
        } catch (RateLimitException e) {
            Log.w(TAG, "Rate limit hit while getting image from Google Images");
        } catch (JSONException e) {
            Log.e(TAG, "JSON Error while getting image from Google Images");
        } catch (IOException e) {
            Log.e(TAG, "IO error while getting image from Google Images");
        }

        if (url == null) {
            // Get from MusicBrainz as both the provider and Google Images can't provide
            AlbumInfo[] albums = null;

            // Query MusicBrainz
            try {
                albums = MusicBrainzClient.getAlbum(artistName, albumName);
            } catch (RateLimitException e) {
                Log.w(TAG, "Can't get from MusicBrainz, rate limited");
            }

            // If we have results, go and fetch one
            if (albums != null && albums.length > 0) {
                AlbumInfo selection = albums[0];

                if (albums.length > 1) {
                    // Try to find if we have an album that has the same track count, otherwise use
                    // the first one
                    for (AlbumInfo albumInfo : albums) {
                        if (albumInfo.track_count == album.getSongsCount()) {
                            selection = albumInfo;
                            break;
                        }
                    }
                }

                // Get the URL
                try {
                    url = MusicBrainzClient.getAlbumArtUrl(selection.id);
                } catch (RateLimitException e) {
                    Log.w(TAG, "Can't get URL from MusicBrainz, rate limited");
                }
            }
        }

        // If we have an URL from either image source, download it and pass it back
        if (url != null) {
            // Download it
            try {
                byte[] imageData = HttpGet.getBytes(url, "", true);
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inMutable = true;
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, opts);
                if (bitmap != null) {
                    result = true;
                    RecyclingBitmapDrawable rcb = ImageCache.getDefault().put(res, getEntityArtKey(listenerRef),
                            bitmap);
                    listener.onArtLoaded(listenerRef, rcb);
                }
            } catch (IOException e) {
                Log.e(TAG, "Error while downloading album art");
            } catch (RateLimitException e) {
                Log.e(TAG, "Rate limited while downloading album art");
            }
        } else {
            ImageCache.getDefault().put(res, getEntityArtKey(listenerRef), (RecyclingBitmapDrawable) null);
            listener.onArtLoaded(listenerRef, null);
            result = true;
        }
    }

    return result;
}