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.dongbang.yutian.activity.CommonScanActivity.java

/**
 *
 *//*from   ww  w  .  java  2s.c  o  m*/
public void scanResult(Result rawResult, Bundle bundle) {
    //????????????reScan()
    //scanManager.reScan();
    //      Toast.makeText(that, "result="+rawResult.getText(), Toast.LENGTH_LONG).show();

    if (!scanManager.isScanning()) { //?????
        //???
        rescan.setVisibility(View.VISIBLE);
        scan_image.setVisibility(View.VISIBLE);
        Bitmap barcode = null;
        byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
        if (compressedBitmap != null) {
            barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
            barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
        }
        scan_image.setImageBitmap(barcode);
    }
    rescan.setVisibility(View.VISIBLE);
    scan_image.setVisibility(View.VISIBLE);
    tv_scan_result.setVisibility(View.VISIBLE);
    tv_scan_result.setText("" + rawResult.getText());
    //        Toast.makeText(this,""+rawResult.getText(),Toast.LENGTH_SHORT).show();
    //      result=rawResult.getText();
    ScanResult.setResult(rawResult.getText());
    finish();
    Intent it = new Intent(this, ProductInfoActivity.class);
    startActivity(it);
}

From source file:com.example.d062654.faciliman._3f_FacilityDetailed.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ll = (RelativeLayout) inflater.inflate(R.layout.facilitydetailed, container, false);
    facarchive = (Button) ll.findViewById(R.id.facarchive);

    factitle = (TextView) ll.findViewById(R.id.factitle);
    factitle.setText(incident.getTitle());
    facplace = (TextView) ll.findViewById(R.id.facplace);
    facplace.setText(incident.getLocation());
    facdetailed_location = (TextView) ll.findViewById(R.id.facdetailed_location);
    facdetailed_location.setText(incident.getExactLocation());
    facdetailed_description = (TextView) ll.findViewById(R.id.facdetailed_description);
    facdetailed_description.setText("Lampe Kaputt");
    facimage = (ImageView) ll.findViewById(R.id.facimage);
    facarchive.setOnClickListener(new View.OnClickListener() {
        @Override//from www.j  a v  a2  s .  c om
        public void onClick(View view) {
            Call<ResponseBody> call = Connection.getApiInterface().archieveIncident(user, incident.getId());
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        Toast.makeText(fragact.getApplicationContext(), "Archivierungsvorgang abgeschlossen",
                                Toast.LENGTH_SHORT).show();
                        facarchive.setEnabled(false);
                    } else if (response.code() == 401) {
                        // Handle unauthorized
                        Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // Handle other responses
                        Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

        }
    });

    Call<ResponseBody> call = Connection.getApiInterface().getFile(user, incident.getId());
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                // Do awesome stuff
                Bitmap bmp = null;

                try {
                    byte[] imgbytes = response.body().bytes();
                    int targetW = facimage.getWidth();
                    int targetH = facimage.getHeight();
                    // bimatp factory
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;

                    bmp = BitmapFactory.decodeByteArray(imgbytes, 0, imgbytes.length, options);

                    int photoW = options.outWidth;
                    int photoH = options.outHeight;
                    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
                    options.inJustDecodeBounds = false;
                    options.inSampleSize = scaleFactor;
                    options.inPurgeable = true;

                    bmp = BitmapFactory.decodeByteArray(imgbytes, 0, imgbytes.length, options);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ImageView image = (ImageView) ll.findViewById(R.id.facimage);

                Matrix matrix = new Matrix();

                matrix.postRotate(90);

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, bmp.getWidth(), bmp.getHeight(), true);

                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                        scaledBitmap.getHeight(), matrix, true);
                facimage.setImageBitmap(rotatedBitmap);

            } else if (response.code() == 401) {
                // Handle unauthorized
                Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                        Toast.LENGTH_SHORT).show();
            } else {
                // Handle other responses
                Toast.makeText(fragact.getApplicationContext(), "Sorry! Failed to capture image",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());

        }
    });
    // Inflate the layout for this fragment
    return ll;
}

From source file:com.truebanana.bitmap.BitmapUtils.java

public static Bitmap decodeBytes(byte[] bytes, int targetWidth, int targetHeight) {
    if (targetWidth > 1 && targetHeight > 1) {
        BitmapFactory.Options options = getBounds(bytes);
        options.inJustDecodeBounds = false;
        options.inSampleSize = getInSampleSize(options, targetWidth, targetHeight);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    } else {/*from   w ww  .  jav a 2  s .c om*/
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
}

From source file:com.secretlisa.lib.utils.BaseImageLoader.java

public Bitmap downloadBitmap(final String imageUrl) {
    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = new DefaultHttpClient();
    // ??//w  ww  .ja va  2  s  .c  o m
    int netType = NetworkUtil.getNetworkType(mContext);
    if (netType == NetworkUtil.TYPE_WAP) {
        String proxyHost = android.net.Proxy.getDefaultHost();
        if (proxyHost != null) {
            HttpHost proxy = new HttpHost(proxyHost, android.net.Proxy.getDefaultPort());
            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) {
            try {
                final byte[] respBytes = getBytes(entity.getContent());
                writeImageFile(imageUrl, respBytes);
                // Decode the bytes and return the bitmap.
                return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, null);
            } finally {
                entity.consumeContent();
            }

        }
    } 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:mobisocial.musubi.objects.PictureObj.java

/**
 * Pass in one of raw or fd as the source of the image.
 * Not thread safe, only call on the ui thread.
 *//*from  w  ww  .  j a v a2 s. c  om*/
protected static void bindImageToView(Context context, ImageView imageView, byte[] raw, FileDescriptor fd) {
    // recycle old images (vs. caching in ImageCache)
    if (imageView.getDrawable() != null) {
        BitmapDrawable d = (BitmapDrawable) imageView.getDrawable();
        if (d != null && d.getBitmap() != null) {
            d.getBitmap().recycle();
        }
    }

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    if (fd != null) {
        BitmapFactory.decodeFileDescriptor(fd, null, options);
    } else {
        BitmapFactory.decodeByteArray(raw, 0, raw.length, options);
    }
    Resources res = context.getResources();

    float scaleFactor;
    if (res.getBoolean(R.bool.is_tablet)) {
        scaleFactor = 3.0f;
    } else {
        scaleFactor = 2.0f;
    }
    DisplayMetrics dm = context.getResources().getDisplayMetrics();
    int pixels = dm.widthPixels;
    if (dm.heightPixels < pixels) {
        pixels = dm.heightPixels;
    }
    int width = (int) (pixels / scaleFactor);
    int height = (int) ((float) width / options.outWidth * options.outHeight);
    int max_height = (int) (AppStateObj.MAX_HEIGHT * dm.density);
    if (height > max_height) {
        width = width * max_height / height;
        height = max_height;
    }

    options.inJustDecodeBounds = false;
    options.inTempStorage = getTempData();
    options.inSampleSize = 1;
    //TODO: lame, can just compute
    while (options.outWidth / (options.inSampleSize + 1) >= width
            && options.outHeight / (options.inSampleSize + 1) >= height) {
        options.inSampleSize++;
    }
    options.inPurgeable = true;
    options.inInputShareable = true;

    Bitmap bm;
    if (fd != null) {
        bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
    } else {
        bm = BitmapFactory.decodeByteArray(raw, 0, raw.length, options);
    }
    imageView.getLayoutParams().width = width + 13;
    imageView.getLayoutParams().height = height + 14;
    imageView.setImageBitmap(bm);
}

From source file:com.doplgangr.secrecy.FileSystem.storage.java

public static Bitmap decodeSampledBitmapFromByte(byte[] stream, int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//from  w  w w  .  j  ava2 s  . c o  m
    BitmapFactory.decodeByteArray(stream, 0, stream.length, options);

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(stream, 0, stream.length, options);
}

From source file:com.benefit.buy.library.http.query.callback.BitmapAjaxCallback.java

private static Bitmap decode(String path, byte[] data, BitmapFactory.Options options, boolean rotate) {
    Bitmap result = null;/*from w w  w.ja  v a 2s . c o  m*/
    if (path != null) {
        result = decodeFile(path, options, rotate);
    } else if (data != null) {
        result = BitmapFactory.decodeByteArray(data, 0, data.length, options);
    }
    if ((result == null) && (options != null) && !options.inJustDecodeBounds) {
        AQUtility.debug("decode image failed", path);
    }
    return result;
}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Bitmap decode(String path, byte[] data, BitmapFactory.Options options, boolean rotate) {

    Bitmap result = null;/*from w  ww .j a v  a2  s  .  com*/

    if (path != null) {

        result = decodeFile(path, options, rotate);

    } else if (data != null) {

        result = BitmapFactory.decodeByteArray(data, 0, data.length, options);

    }

    if (result == null && options != null && !options.inJustDecodeBounds) {
        AQUtility.debug("decode image failed", path);
    }

    return result;
}

From source file:com.secretlisa.lib.utils.BaseImageLoader.java

public Bitmap downloadBitmapFromWeb(String imageUrl) {
    HttpRequest request = new HttpRequest(mContext);
    Response response = null;//from   w  ww. jav a2 s .c o  m
    try {
        response = request.httpRequest(imageUrl, "GET", null, null);
        final byte[] respBytes = getBytes(response.getInputStream());
        writeImageFile(imageUrl, respBytes);
        // Decode the bytes and return the bitmap.
        return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, null);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
    return null;
}

From source file:com.android.volley.toolbox.ImageRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *///from  ww  w.ja  v  a  2 s.c om
private Response<Bitmap> doParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap = null;
    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;
        // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
        // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
        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));
    }
}