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) 

Source Link

Document

Decode an immutable bitmap from the specified byte array.

Usage

From source file:ca.ualberta.app.activity.CreateQuestionActivity.java

@Override
public void onStart() {
    super.onStart();
    Intent intent = getIntent();/*  ww  w  . j ava  2 s.c  o  m*/
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            questionID = extras.getLong(QUESTION_ID);
            String questionTitle = extras.getString(QUESTION_TITLE);
            String questionContent = extras.getString(QUESTION_CONTENT);
            try {
                byte[] imageByteArray = Base64.decode(extras.getByteArray(IMAGE), Base64.NO_WRAP);
                image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                scaleImage(THUMBIMAGESIZE, THUMBIMAGESIZE, true);
                imageView.setVisibility(View.VISIBLE);
                imageView.setImageBitmap(imageThumb);
            } catch (Exception e) {
            }
            titleText.setText(questionTitle);
            contentText.setText(questionContent);
            edit = true;
        }
    }
}

From source file:com.siahmsoft.soundroid.sdk7.util.ImageUtilities.java

/**
 * Loads an image from the specified URL with the specified cookie.
 *
 * @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.
 *//*from  w  w  w .j av  a  2s  . c  o  m*/
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();
                    expiring.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                }
            } catch (IOException e) {
                android.util.Log.e(LOG_TAG, "Could not load image from " + url, e);
            } 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.airbop.client.GCMIntentService.java

/**
 * Decode a base64 string into a Bitmap/* www .j  a  v a  2 s.c  o m*/
 */
private static Bitmap decodeImage(String image_data) {
    // Decode the encoded string into largeIcon
    Bitmap largeIcon = null;
    if ((image_data != null) && (!image_data.equals(""))) {
        byte[] decodedImage = Base64.decode(image_data, Base64.DEFAULT);
        if (decodedImage != null) {
            largeIcon = BitmapFactory.decodeByteArray(decodedImage, 0, decodedImage.length);
        }
    }
    return largeIcon;
}

From source file:com.oxgcp.photoList.PhotolistModule.java

@Kroll.method
public TiBlob getThumbnail(String fileName) {
    try {/*from   w ww  . j  a  v  a  2  s  . c  o m*/
        ExifInterface exif = new ExifInterface(fileName);

        byte[] thumbnail = exif.getThumbnail();

        Log.d("TiAPI", "thumbnail's length: " + thumbnail.length);

        return TiBlob.blobFromImage(BitmapFactory.decodeByteArray(thumbnail, 0, thumbnail.length));
    } catch (Exception e) {
        return null;
    }
}

From source file:de.madvertise.android.sdk.MadView.java

private void showStaticBannerView() {
    MadUtil.logMessage(null, Log.DEBUG, "Add static banner");

    Bitmap bannerBitmap = BitmapFactory.decodeByteArray(currentAd.getImageByteArray(), 0,
            currentAd.getImageByteArray().length);
    StaticBannerView staticBannerView = new StaticBannerView(getContext(), bannerBitmap);

    removeAllViews();/*from  w w w . j a  va2 s.com*/
    addView(staticBannerView);
}

From source file:cn.edu.szjm.support.images.remote.RemoteImageLoader.java

/**
 * Creates a new ImageLoader that is backed by an {@link ImageCache}. The cache will by default
 * cache to the device's external storage, and expire images after 1 day. You can set useCache
 * to false and then supply your own image cache instance via {@link #setImageCache(ImageCache)}
 * , or fine-tune the default one through {@link #getImageCache()}.
 * /*w ww  .  java2  s .  c  om*/
 * @param context
 *            the current context
 * @param createCache
 *            whether to create a default {@link ImageCache} used for caching
 */
public RemoteImageLoader(final Context context, boolean usingCache) {
    //        executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
    this.usingCache = usingCache;
    if (usingCache) {
        imageCache = SharedImageCache.getSharedImageCache();
    } else {
        imageCache = null;
    }
    errorDrawable = context.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
    task = new IgnitedAsyncTask<Context, Void, Void, Bitmap>() {
        @Override
        public boolean onTaskCompleted(Bitmap bitmap) {
            if (!cancel) {
                handler.handleImageLoaded(bitmap, null);
            }
            return true;
        }

        @Override
        public boolean onTaskFailed(Exception error) {
            if (task != null) {
                Log.d("test", "failed " + task.getStatus() + task);
            }
            return true;
        }

        //            @Override
        //            protected void onCancelled() {
        //               if(task != null) {
        //                  Log.d("test", "cancel "+task.getStatus() + task + isCancelled());
        //               }
        //            }
    };
    IgnitedAsyncTaskCallable<Context, Void, Void, Bitmap> callable = new IgnitedAsyncTaskCallable<Context, Void, Void, Bitmap>() {
        @Override
        public Bitmap call(IgnitedAsyncTask<Context, Void, Void, Bitmap> task) throws Exception {
            // TODO Auto-generated method stub
            if (cancel) {
                return null;
            }
            Bitmap bitmap = null;
            if (imageCache != null) {
                // at this point we know the image is not in memory, but it could be cached to SD card
                bitmap = imageCache.getBitmap(imageUrl);
            }
            if (bitmap == null) {
                bitmap = downloadImage(context);
            }
            return bitmap;
        }

        protected Bitmap downloadImage(Context context) {
            int timesTried = 1;
            while (timesTried <= numRetries && !cancel) {
                try {
                    if (cancel) {
                        return null;
                    }
                    byte[] imageData = retrieveImageData(context);
                    if (imageData == null) {
                        break;
                    }
                    if (imageCache != null) {
                        imageCache.put(imageUrl, imageData);
                    }
                    return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                } catch (Throwable e) {
                    Log.w(LOG_TAG, "download for " + imageUrl + " failed (attempt " + timesTried + ")");
                    e.printStackTrace();
                    SystemClock.sleep(DEFAULT_RETRY_HANDLER_SLEEP_TIME);
                    timesTried++;
                }
            }
            return null;
        }

        protected byte[] retrieveImageData(Context context) throws IOException {
            IgnitedHttp http = new IgnitedHttp(context);
            http.disableResponseCache(true);
            IgnitedHttpRequest request = http.get(imageUrl, true).retries(3).expecting(200);
            request.setWrapResponse(false);
            if (cancel) {
                return null;
            }
            HttpResponse response = (HttpResponse) request.send();
            HttpEntity entity = response.getEntity();
            //                URL url = new URL(imageUrl);
            //                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // determine the image size and allocate a buffer
            int fileSize = (int) entity.getContentLength();
            Log.d(LOG_TAG, "fetching image " + imageUrl + " ("
                    + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")");
            BufferedInputStream istream = new BufferedInputStream(entity.getContent());
            try {
                if (fileSize <= 0) {
                    Log.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of "
                            + defaultBufferSize + " bytes");
                    ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize);
                    byte[] buffer = new byte[defaultBufferSize];
                    int bytesRead = 0;
                    while (bytesRead != -1) {
                        if (cancel) {
                            return null;
                        }
                        bytesRead = istream.read(buffer, 0, defaultBufferSize);
                        if (bytesRead > 0)
                            buf.write(buffer, 0, bytesRead);
                    }
                    return buf.toByteArray();
                } else {
                    byte[] imageData = new byte[fileSize];

                    int bytesRead = 0;
                    int offset = 0;
                    while (bytesRead != -1 && offset < fileSize) {
                        if (cancel) {
                            return null;
                        }
                        bytesRead = istream.read(imageData, offset, fileSize - offset);
                        offset += bytesRead;
                    }
                    return imageData;
                }
            } finally {
                // clean up
                try {
                    istream.close();
                    //connection.disconnect();
                } catch (Exception ignore) {
                }
            }
        }
    };
    task.setCallable(callable);
}

From source file:cc.flydev.launcher.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG)// w ww .  j a  v a  2 s  .c o  m
            Log.d(TAG, "Getting and clearing APPS_PENDING_INSTALL: " + strings);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.ayuget.redface.ui.misc.ImageMenuHandler.java

/**
 * Saves image from network using OkHttp. Picasso is not used because it would strip away the
 * EXIF data once the image is saved (Picasso directly gives us a Bitmap).
 *///from  w w  w.ja v  a 2s.  c  om
private void saveImageFromNetwork(final File mediaFile, final Bitmap.CompressFormat targetFormat,
        final boolean compressAsPng, final boolean notifyUser, final boolean broadcastSave,
        final ImageSavedCallback imageSavedCallback) {
    OkHttpClient okHttpClient = new OkHttpClient();

    final Request request = new Request.Builder().url(imageUrl).build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            SnackbarHelper.makeError(activity, R.string.error_saving_image).show();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            final byte[] imageBytes = response.body().bytes();

            Timber.d("Image successfully decoded, requesting WRITE_EXTERNAL_STORAGE permission to save image");

            RxPermissions.getInstance(activity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean granted) {
                            if (granted) {
                                Timber.d("WRITE_EXTERNAL_STORAGE granted, saving image to disk");

                                try {
                                    Timber.d("Saving image to %s", mediaFile.getAbsolutePath());

                                    if (compressAsPng) {
                                        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0,
                                                imageBytes.length);
                                        StorageHelper.storeImageToFile(bitmap, mediaFile, targetFormat);
                                    } else {
                                        StorageHelper.storeImageToFile(imageBytes, mediaFile);
                                    }

                                    if (broadcastSave) {
                                        // First, notify the system that a new image has been saved
                                        // to external storage. This is important for user experience
                                        // because it makes the image visible in the system gallery
                                        // app.
                                        StorageHelper.broadcastImageWasSaved(activity, mediaFile, targetFormat);
                                    }

                                    if (notifyUser) {
                                        // Then, notify the user with an enhanced snackbar, allowing
                                        // him (or her) to open the image in his favorite app.
                                        Snackbar snackbar = SnackbarHelper.makeWithAction(activity,
                                                R.string.image_saved_successfully,
                                                R.string.action_snackbar_open_image,
                                                new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Intent intent = new Intent();
                                                        intent.setAction(Intent.ACTION_VIEW);
                                                        intent.setDataAndType(
                                                                Uri.parse("file://"
                                                                        + mediaFile.getAbsolutePath()),
                                                                "image/*");
                                                        activity.startActivity(intent);
                                                    }
                                                });
                                        snackbar.show();
                                    }

                                    notifyImageWasSaved(imageSavedCallback, mediaFile, targetFormat);
                                } catch (IOException e) {
                                    Timber.e(e, "Unable to save image to external storage");
                                    SnackbarHelper.makeError(activity, R.string.error_saving_image).show();
                                }
                            } else {
                                Timber.w("WRITE_EXTERNAL_STORAGE denied, unable to save image");
                                SnackbarHelper
                                        .makeError(activity, R.string.error_saving_image_permission_denied)
                                        .show();
                            }
                        }
                    });
        }
    });
}

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

private boolean getFreeArt(final Resources res, final BoundEntity ent, final IAlbumArtCacheListener listener) {
    new Thread() {
        public void run() {
            try {
                byte[] bytes = HttpGet.getBytes("http://lorempixel.com/600/600/abstract/", "", false);
                if (bytes != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    if (bitmap != null) {
                        RecyclingBitmapDrawable rbd = ImageCache.getDefault().put(res, getEntityArtKey(ent),
                                bitmap);
                        listener.onArtLoaded(ent, rbd);
                    } else {
                        listener.onArtLoaded(ent, null);
                    }/*from  w w w  . ja  va  2 s . c  om*/
                } else {
                    listener.onArtLoaded(ent, null);
                }
            } catch (IOException | RateLimitException ignore) {
                listener.onArtLoaded(ent, null);
            }
        }
    }.start();

    return true;
}