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:Main.java

public static Bitmap getCompressBitmap(Bitmap bitmap, File file, int quality, int fileSize) {
    Bitmap bmp = null;/*www.ja  v a2s. com*/
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    boolean result = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
    LOG("getCompressBitmap result: " + result);
    try {
        if (file != null) {
            if (result) {
                byte[] bt = bos.toByteArray();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(bt);
                fos.close();

                LOG("file.length(): " + file.length());

                if (file.length() > fileSize) {
                    bmp = getCompressBitmap(bmp, file, (int) (quality * 0.8), fileSize);
                } else {
                    bmp = BitmapFactory.decodeFile(file.getPath());
                }
            }

        } else {
            bmp = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
        }
        bos.close();
    } catch (Exception e) {
        LOG("getCompressBitmap result: e" + e.toString());
        e.printStackTrace();
        return null;
    }
    return bmp;
}

From source file:Main.java

@SuppressLint("NewApi")
public static Bitmap NV21ToRGBABitmap(byte[] nv21, int width, int height, Context context) {

    TimingLogger timings = new TimingLogger(TIMING_LOG_TAG, "NV21ToRGBABitmap");

    Rect rect = new Rect(0, 0, width, height);

    try {/* ww w. j ava 2 s  . c  o  m*/
        Class.forName("android.renderscript.Element$DataKind").getField("PIXEL_YUV");
        Class.forName("android.renderscript.ScriptIntrinsicYuvToRGB");
        byte[] imageData = nv21;
        if (mRS == null) {
            mRS = RenderScript.create(context);
            mYuvToRgb = ScriptIntrinsicYuvToRGB.create(mRS, Element.U8_4(mRS));
            Type.Builder tb = new Type.Builder(mRS,
                    Element.createPixel(mRS, Element.DataType.UNSIGNED_8, Element.DataKind.PIXEL_YUV));
            tb.setX(width);
            tb.setY(height);
            tb.setMipmaps(false);
            tb.setYuvFormat(ImageFormat.NV21);
            ain = Allocation.createTyped(mRS, tb.create(), Allocation.USAGE_SCRIPT);
            timings.addSplit("Prepare for ain");
            Type.Builder tb2 = new Type.Builder(mRS, Element.RGBA_8888(mRS));
            tb2.setX(width);
            tb2.setY(height);
            tb2.setMipmaps(false);
            aOut = Allocation.createTyped(mRS, tb2.create(), Allocation.USAGE_SCRIPT & Allocation.USAGE_SHARED);
            timings.addSplit("Prepare for aOut");
            bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
            timings.addSplit("Create Bitmap");
        }
        ain.copyFrom(imageData);
        timings.addSplit("ain copyFrom");
        mYuvToRgb.setInput(ain);
        timings.addSplit("setInput ain");
        mYuvToRgb.forEach(aOut);
        timings.addSplit("NV21 to ARGB forEach");
        aOut.copyTo(bitmap);
        timings.addSplit("Allocation to Bitmap");
    } catch (Exception e) {
        YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
        timings.addSplit("NV21 bytes to YuvImage");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvImage.compressToJpeg(rect, 90, baos);
        byte[] cur = baos.toByteArray();
        timings.addSplit("YuvImage crop and compress to Jpeg Bytes");

        bitmap = BitmapFactory.decodeByteArray(cur, 0, cur.length);
        timings.addSplit("Jpeg Bytes to Bitmap");
    }

    timings.dumpToLog();
    return bitmap;
}

From source file:com.vk.sdk.api.httpClient.VKImageOperation.java

/**
 * Set listener for current operation//from w  w  w. jav  a  2  s . com
 * @param listener Listener subclasses VKHTTPOperationCompleteListener
 */
public void setImageOperationListener(final VKImageOperationListener listener) {
    this.setCompleteListener(new VKOperationCompleteListener() {
        @Override
        public void onComplete() {
            if (VKImageOperation.this.state() != VKOperationState.Finished || mLastException != null) {
                listener.onError(VKImageOperation.this, generateError(mLastException));
            } else {
                byte[] response = getResponseData();
                Bitmap captchaImage = BitmapFactory.decodeByteArray(response, 0, response.length);
                if (imageDensity > 0) {
                    captchaImage = Bitmap.createScaledBitmap(captchaImage,
                            (int) (captchaImage.getWidth() * imageDensity),
                            (int) (captchaImage.getHeight() * imageDensity), true);
                }
                final Bitmap result = captchaImage;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onComplete(VKImageOperation.this, result);
                    }
                });
            }
        }
    });
}

From source file:ca.christophersaunders.tutorials.sqlite.picasa.PicasaImage.java

public Bitmap getImage() {
    if (image == null && imageLocation != null) {
        getImageBytes();//from w  ww  .  jav  a  2 s . co m
        image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    }
    return image;
}

From source file:com.android.dialer.lookup.yellowpages.YellowPagesReverseLookup.java

/**
 * Lookup image//from  w w  w.  j  a  v  a 2 s .  c  o m
 *
 * @param context The application context
 * @param uri The image URI
 */
public Bitmap lookupImage(Context context, Uri uri) {
    if (uri == null) {
        throw new NullPointerException("URI is null");
    }

    Log.e(TAG, "Fetching " + uri);

    String scheme = uri.getScheme();

    if (scheme.startsWith("http")) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri.toString());

        try {
            HttpResponse response = client.execute(request);

            int responseCode = response.getStatusLine().getStatusCode();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            byte[] responseBytes = out.toByteArray();

            if (responseCode == HttpStatus.SC_OK) {
                Bitmap bmp = BitmapFactory.decodeByteArray(responseBytes, 0, responseBytes.length);
                return bmp;
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
        try {
            ContentResolver cr = context.getContentResolver();
            Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
            return bmp;
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    }

    return null;
}

From source file:com.strato.hidrive.api.bll.file.GetThumbnailGateway.java

@Override
protected ResponseHandler<String> createResponseHandler() {
    super.createResponseHandler();
    return new ResponseHandler<String>() {
        @Override/*from w ww  .j  a va 2s  .  com*/
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                byte[] bytes = EntityUtils.toByteArray(entity);
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
            return DONE_JSON_RESULT;
        }
    };
}

From source file:com.grouzen.android.serenity.Response.java

public Bitmap toBitmap() {
    return BitmapFactory.decodeByteArray(mData, 0, mData.length);
}

From source file:Main.java

static public Bitmap NV21ToRGBABitmap(byte[] nv21, int width, int height) {
    YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    yuvImage.compressToJpeg(new Rect(0, 0, width, height), 100, baos);
    byte[] cur = baos.toByteArray();
    return BitmapFactory.decodeByteArray(cur, 0, cur.length);
}

From source file:com.coodesoft.notee.MyImageGetter.java

@Override
public Drawable getDrawable(String source) {
    Drawable d = null;/*from  w  w  w .  j  a  v a  2 s .c  o m*/

    String strSrcLeft5 = source.substring(0, 5);

    // data
    if (strSrcLeft5.equalsIgnoreCase("data:")) {
        InputStream is = new ByteArrayInputStream(source.getBytes());

        //d = Drawable.createFromStream(is, null);
        //d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        //Bitmap dBitmap = BitmapFactory.decodeByteArray(data, 0, length);
        int nPosComma = source.indexOf(',');
        if (nPosComma > 0) {
            byte[] arrBuffer = Base64.decode(source.substring(nPosComma + 1), Base64.DEFAULT);
            //byte[] arrBuffer = Base64Coder.decode(source.substring(nPosComma + 1));
            Bitmap dBitmap = BitmapFactory.decodeByteArray(arrBuffer, 0, arrBuffer.length);
            d = new BitmapDrawable(dBitmap);
            d.setBounds(0, 0, dBitmap.getWidth(), dBitmap.getHeight());
        }

    } else {
        // url

        try {

            InputStream is = (InputStream) new URL(source).getContent();
            Bitmap dBitmap = BitmapFactory.decodeStream(is);
            if (dBitmap == null) {
                d = Resources.getSystem().getDrawable(android.R.drawable.picture_frame);
            } else {
                d = new BitmapDrawable(dBitmap);
                d.setBounds(0, 0, dBitmap.getWidth(), dBitmap.getHeight());
            }

            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        /*
         URLDrawable urlDrawable = new URLDrawable();
                
         // get the actual source
         ImageGetterAsyncTask asyncTask = 
        new ImageGetterAsyncTask( urlDrawable);
                
         asyncTask.execute(source);
                
         // return reference to URLDrawable where I will change with actual image from
         // the src tag
         return urlDrawable;
         */

    }

    return d;
}

From source file:com.ferjuarez.androidthingsdemo.PhotoEntryAdapter.java

@Override
protected void populateViewHolder(DoorbellEntryViewHolder viewHolder, PhotoEntry model, int position) {
    // Display the timestamp
    if (model != null && model.getTimestamp() != null) {
        CharSequence prettyTime = DateUtils.getRelativeDateTimeString(mApplicationContext, model.getTimestamp(),
                DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
        viewHolder.time.setText(prettyTime);

        // Display the image
        if (model.getThumbnail() != null) {
            // Decode image data encoded by the Cloud Vision library
            byte[] imageBytes = Base64.decode(model.getThumbnail(), Base64.NO_WRAP | Base64.URL_SAFE);
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            if (bitmap != null) {
                viewHolder.image.setImageBitmap(bitmap);
            } else {
                Drawable placeholder = ContextCompat.getDrawable(mApplicationContext, R.mipmap.ic_launcher);
                viewHolder.image.setImageDrawable(placeholder);
            }//from w ww.j  a v  a2  s .c om
        }
    }

    // Display the metadata
    /*if (model.getAnnotations() != null) {
    ArrayList<String> keywords = new ArrayList<>(model.getAnnotations().keySet());
            
    int limit = Math.min(keywords.size(), 3);
    viewHolder.metadata.setText(TextUtils.join("\n", keywords.subList(0, limit)));
    } else {
    viewHolder.metadata.setText("no annotations yet");
    }*/
}