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:com.example.android.camera.CameraActivity.java

public static void loadImage(String classes, String username) {

    FaceMatchClient.getImage("/img/" + classes + "/original/" + username + "_original.JPEG",
            new BinaryHttpResponseHandler(allowedContentTypes) {

                @Override// w w w.  j  av  a  2 s.c  o m
                public void onSuccess(byte[] fileData) {
                    Bitmap bmp = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
                    ;
                    imageView.setImageBitmap(bmp);
                }
            });
}

From source file:com.app_software.chromisstock.ProductDetailFragment.java

private void setViewsContent() {

    if (mItem != null) {
        m_edit_name.setText(mItem.getValueString(StockProduct.NAME));
        m_edit_reference.setText(mItem.getValueString(StockProduct.REFERENCE));
        m_edit_barcode.setText(mItem.getValueString(StockProduct.CODE));
        m_edit_instock.setText(String.format("%.0f", mItem.getValueDouble(StockProduct.QTY_INSTOCK)));
        m_edit_minqty.setText(String.format("%.0f", mItem.getValueDouble(StockProduct.QTY_MIN)));
        m_edit_maxqty.setText(String.format("%.0f", mItem.getValueDouble(StockProduct.QTY_MAX)));
        m_edit_pricebuy.setText(String.format("%.2f", mItem.getValueDouble(StockProduct.PRICEBUY)));
        m_edit_pricesell.setText(String.format("%.2f", mItem.getValueDouble(StockProduct.PRICESELL)));

        DatabaseHandler.Location loc = m_db.getLocation(mItem.getValueString(StockProduct.LOCATION));
        if (loc != null) {
            m_txt_location.setText(loc.Name);
        }/*from  w w  w  .jav a2s  .  c  o  m*/

        m_LastTaxCat = mItem.getValueString(StockProduct.TAXCAT);
        m_taxSpinner.setSelection(m_taxAdaptor.getPosition((m_LastTaxCat)));

        m_LastCategory = mItem.getValueString(StockProduct.CATEGORY);
        m_categorySpinner.setSelection(m_categoryAdaptor.getPosition((m_LastCategory)));

        byte[] image = mItem.getValueByteArray(StockProduct.IMAGE);
        if (image != null) {
            Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
            m_image.setImageBitmap(bmp);
        }

        // Force entry of name field
        if (!m_nameChecked && TextUtils.isEmpty(mItem.getValueString(StockProduct.NAME))) {
            m_nameChecked = true;
            onEditItem(m_edit_name);
        }
    }

}

From source file:com.ivanmagda.inventory.ui.ProductEditor.java

private void updateUiWithProduct(Product product) {
    mNameEditText.setText(product.getName());
    mPriceEditText.setText(String.valueOf(product.getPrice()));
    mQuantityEditText.setText(String.valueOf(product.getQuantity()));
    mSupplierEmailEditText.setText(product.getSupplier());
    mSoldQuantityTextView.setText(String.valueOf(product.getSoldQuantity()));

    byte[] bytes = mProduct.getPicture();
    if (bytes != null) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        mProductImageView.setImageBitmap(bitmap);
    }//  w  w  w  . j  a  v  a2s.  co  m
}

From source file:com.nttec.everychan.chans.infinity.InfinityModule.java

@Override
public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener,
        CancellableTask task) throws Exception {

    String url = getUsingUrl() + "settings.php?board=" + boardName;
    JSONObject json;/*from   w ww.jav a2 s  . c o m*/
    try {
        json = downloadJSONObject(url, false, listener, task);
    } catch (Exception e) {
        json = new JSONObject();
    }

    if (needTorCaptcha) {
        url = getUsingUrl() + "dnsbls_bypass.php";
        String response = HttpStreamer.getInstance().getStringFromUrl(url, HttpRequestModel.DEFAULT_GET,
                httpClient, listener, task, false);
        Matcher base64Matcher = CAPTCHA_BASE64.matcher(response);
        Matcher cookieMatcher = CAPTCHA_COOKIE.matcher(response);
        if (base64Matcher.find() && cookieMatcher.find()) {
            byte[] bitmap = Base64.decode(base64Matcher.group(1), Base64.DEFAULT);
            torCaptchaCookie = cookieMatcher.group(1);
            CaptchaModel captcha = new CaptchaModel();
            captcha.type = CaptchaModel.TYPE_NORMAL;
            captcha.bitmap = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
            return captcha;
        }
    }
    needNewthreadCaptcha = ((threadNumber == null && (json.getBoolean("new_thread_capt")))
            || (Boolean) json.getJSONObject("captcha").get("enabled"));
    if (needNewthreadCaptcha) {
        url = getUsingUrl()
                + "8chan-captcha/entrypoint.php?mode=get&extra=abcdefghijklmnopqrstuvwxyz&nojs=true";
        HttpRequestModel request = HttpRequestModel.builder().setGET()
                .setCustomHeaders(new Header[] { new BasicHeader(HttpHeaders.CACHE_CONTROL, "max-age=0") })
                .build();
        String response = HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, listener, task,
                false);
        Matcher base64Matcher = CAPTCHA_BASE64.matcher(response);
        Matcher captchaIdMatcher = CAPTCHA_ID.matcher(response);
        if (base64Matcher.find() && captchaIdMatcher.find()) {
            byte[] bitmap = Base64.decode(base64Matcher.group(1), Base64.DEFAULT);
            newThreadCaptchaId = captchaIdMatcher.group(1);
            CaptchaModel captcha = new CaptchaModel();
            captcha.type = CaptchaModel.TYPE_NORMAL;
            captcha.bitmap = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
            return captcha;
        }
    }
    return null;
}

From source file:com.android.ex.chips.RecipientAlternatesAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int position = cursor.getPosition();

    TextView display = (TextView) view.findViewById(android.R.id.title);
    ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
    RecipientEntry entry = getRecipientEntry(position);
    if (position == 0) {
        display.setText(cursor.getString(Queries.Query.NAME));
        display.setVisibility(View.VISIBLE);

        byte[] photoBytes = mPhotoCacheMap.get(entry.getPhotoThumbnailUri());
        if (photoBytes != null && imageView != null) {
            Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
            imageView.setImageBitmap(photo);
        } else {//  w  w w.j a  va  2  s  . com
            imageView.setImageResource(R.drawable.ic_contact_picture);
            if (entry.getPhotoThumbnailUri() != null)
                fetchPhotoAsync(entry, entry.getPhotoThumbnailUri());
        }
        imageView.setVisibility(View.VISIBLE);
    } else {
        display.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
    }
    TextView destination = (TextView) view.findViewById(android.R.id.text1);
    destination.setText(cursor.getString(Queries.Query.DESTINATION));

    TextView destinationType = (TextView) view.findViewById(android.R.id.text2);
    if (destinationType != null) {
        destinationType.setText(
                mQuery.getTypeLabel(context.getResources(), cursor.getInt(Queries.Query.DESTINATION_TYPE),
                        cursor.getString(Queries.Query.DESTINATION_LABEL)).toString().toUpperCase());
    }
}

From source file:com.DGSD.DGUtils.ImageDownloader.ImageLoader.java

protected Bitmap downloadImage() {
    int timesTried = 1;

    while (timesTried <= numRetries) {
        try {//  ww  w  .  j  av  a2 s.c o  m
            byte[] imageData = retrieveImageData();

            if (imageData != null) {
                imageCache.put(imageUrl, imageData);
            } else {
                break;
            }

            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;
}

From source file:com.akop.bach.ImageCache.java

public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) {
    if (imageUrl == null || imageUrl.length() < 1)
        return null;

    File file = getCacheFile(imageUrl, cachePol);

    // See if it's in the local cache 
    // (but only if not being forced to refresh)
    if (!cachePol.bypassCache && file.canRead()) {
        if (App.getConfig().logToConsole())
            App.logv("Cache hit: " + file.getName());

        try {/*from  w  w w .  j  a  va2 s . c  om*/
            if (!cachePol.expired(System.currentTimeMillis(), file.lastModified()))
                return BitmapFactory.decodeFile(file.getAbsolutePath());
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    // Fetch the image
    byte[] blob;
    int length;

    try {
        HttpClient client = new IgnorantHttpClient();

        HttpParams params = client.getParams();
        params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)");

        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS);

        HttpResponse resp = client.execute(new HttpGet(imageUrl));
        HttpEntity entity = resp.getEntity();

        if (entity == null)
            return null;

        InputStream stream = entity.getContent();
        if (stream == null)
            return null;

        try {
            if ((length = (int) entity.getContentLength()) <= 0) {
                // Length is negative, perhaps content length is not set
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

                int chunkSize = 5000;
                byte[] chunk = new byte[chunkSize];

                for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize))
                    byteStream.write(chunk, 0, r);

                blob = byteStream.toByteArray();
            } else {
                // We know the length
                blob = new byte[length];

                // Read the stream until nothing more to read
                for (int r = 0; r < length; r += stream.read(blob, r, length - r))
                    ;
            }
        } finally {
            stream.close();
            entity.consumeContent();
        }
    } catch (IOException e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();

        return null;
    }

    // if (file.canWrite())
    {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file);

            if (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) {
                Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
                float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight();

                int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio)
                        : cachePol.resizeWidth;
                int newHeight = (cachePol.resizeHeight <= 0)
                        ? (int) ((float) cachePol.resizeWidth / aspectRatio)
                        : cachePol.resizeHeight;

                Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                resized.compress(Bitmap.CompressFormat.PNG, 100, fos);

                return resized;
            } else {
                fos.write(blob);
            }

            if (App.getConfig().logToConsole())
                App.logv("Wrote to cache: " + file.getName());
        } catch (IOException e) {
            if (App.getConfig().logToConsole())
                e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    Bitmap bmp = null;

    try {
        bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
    } catch (Exception e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();
    }

    return bmp;
}

From source file:com.carlrice.reader.fragment.EntryFragment.java

private void refreshUI(Cursor entryCursor) {
    if (entryCursor != null) {
        String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos)
                : entryCursor.getString(mFeedNamePos);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.setTitle(feedTitle);/*  ww w  .j  av  a2 s  .  c om*/

        byte[] iconBytes = entryCursor.getBlob(mFeedIconPos);
        Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
        UiUtils.getFaviconPalette(bitmap, mToolbarPaletteListener);

        mFavorite = entryCursor.getInt(mIsFavoritePos) == 1;
        activity.invalidateOptionsMenu();

        // Listen the mobilizing task
        if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) {
            showSwipeProgress();

            // If the service is not started, start it here to avoid an infinite loading
            if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
                Application.context().startService(new Intent(Application.context(), FetcherService.class)
                        .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            }
        } else {
            hideSwipeProgress();
        }

        // Mark the article as read
        if (entryCursor.getInt(mIsReadPos) != 1) {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver cr = Application.context().getContentResolver();
                    cr.update(uri, FeedData.getReadContentValues(), null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }).start();
        }
    }
}

From source file:at.flack.receiver.SmsReceiver.java

public final Bitmap fetchThumbnail(Context context, String address) {
    Integer id = fetchThumbnailId(context, address);
    if (id == null)
        return null;
    final Uri uri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id);
    final Cursor cursor = context.getContentResolver().query(uri, PHOTO_BITMAP_PROJECTION, null, null, null);

    try {//from  www  .j  a v a  2s  . c  o m
        Bitmap thumbnail = null;
        if (cursor.moveToFirst()) {
            final byte[] thumbnailBytes = cursor.getBlob(0);
            if (thumbnailBytes != null) {
                thumbnail = BitmapFactory.decodeByteArray(thumbnailBytes, 0, thumbnailBytes.length);
            }
        }
        return thumbnail;
    } finally {
        cursor.close();
    }
}

From source file:com.s8launch.cheil.facetracker.MultiTrackerActivity.java

@Override
public void onPictureTaken(byte[] data) {
    //  try {/*w  ww.ja  v  a2s.  c o  m*/
    Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    Bitmap newImage = Bitmap.createBitmap(cameraBitmap.getWidth(), cameraBitmap.getHeight(),
            Bitmap.Config.ARGB_8888);

    Bitmap overlayBitmap = this.getBitmapFromView(mGraphicOverlay);

    Bitmap overlayScaledBitmap = Bitmap.createScaledBitmap(overlayBitmap, cameraBitmap.getWidth(),
            cameraBitmap.getHeight(), true);
    Canvas canvas = new Canvas(newImage);
    canvas.drawBitmap(cameraBitmap, 0, 0, null);
    canvas.drawBitmap(overlayScaledBitmap, 0, 0, null);

    File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    storagePath.mkdirs();
    String finalName = Long.toString(System.currentTimeMillis());
    File myImage = new File(storagePath, finalName + ".jpg");

    String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + finalName + ".jpg";

    try {
        FileOutputStream fos = new FileOutputStream(myImage);
        newImage.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        fos.close();
    } catch (IOException e) {
        Toast.makeText(MultiTrackerActivity.this, "Pic not saved", Toast.LENGTH_SHORT).show();
        return;
    }
    Toast.makeText(MultiTrackerActivity.this, "Pic saved in: " + photoPath, Toast.LENGTH_SHORT).show();

    newImage.recycle();
    newImage = null;
    cameraBitmap.recycle();
    cameraBitmap = null;
}