Java Code Examples for android.graphics.BitmapFactory#decodeByteArray()

The following examples show how to use android.graphics.BitmapFactory#decodeByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtil.java    From XposedNavigationBar with GNU General Public License v3.0 9 votes vote down vote up
/**
 * 缩放图片
 *
 * @param bmByte
 * @param scale
 * @return
 */
public static Bitmap zoomBitmap(byte[] bmByte, int scale) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = false;
    Bitmap bm = BitmapFactory.decodeByteArray(bmByte, 0, bmByte.length, opts);

    Matrix matrix = new Matrix();
    matrix.postScale((float) (scale / 100.0), (float) (scale / 100.0));
    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
    return bitmap;
}
 
Example 2
Source File: BitmapUtils.java    From BigApp_Discuz_Android with Apache License 2.0 8 votes vote down vote up
public static Bitmap Bytes2Bimap(byte[] b) {

        Bitmap bitmap = null;
        if (b.length != 0) {
            try {
                BitmapFactory.Options options = new Options();
                options.inDither = false; /* 不进行图片抖动处理 */
                options.inPreferredConfig = null; /* 设置让解码器以最佳方式解码 */
                options.inSampleSize = 4; /* 图片长宽方向缩小倍数 */
                bitmap = BitmapFactory.decodeByteArray(b, 0, b.length, options);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }

        return bitmap;
    }
 
Example 3
Source File: Fetcher.java    From tns-core-modules-widgets with Apache License 2.0 8 votes vote down vote up
public static Bitmap decodeSampledBitmapFromByteArray(byte[] buffer, int reqWidth, int reqHeight,
        boolean keepAspectRatio, Cache cache) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    // If we're running on Honeycomb or newer, try to use inBitmap
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }

    final Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);

    InputStream is = new ByteArrayInputStream(buffer);
    ExifInterface ei = getExifInterface(is);

    return scaleAndRotateBitmap(bitmap, ei, reqWidth, reqHeight, keepAspectRatio);
}
 
Example 4
Source File: ConvertUtils.java    From AndroidPicker with MIT License 8 votes vote down vote up
public static Bitmap toBitmap(byte[] bytes, int width, int height) {
    Bitmap bitmap = null;
    if (bytes.length != 0) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 不进行图片抖动处理
            options.inDither = false;
            // 设置让解码器以最佳方式解码
            options.inPreferredConfig = null;
            if (width > 0 && height > 0) {
                options.outWidth = width;
                options.outHeight = height;
            }
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            bitmap.setDensity(96);// 96 dpi
        } catch (Exception e) {
            LogUtils.error(e);
        }
    }
    return bitmap;
}
 
Example 5
Source File: MBTilesTileDataSource.java    From geopaparazzi with GNU General Public License v3.0 8 votes vote down vote up
@Override
public void query(MapTile tile, ITileDataSink sink) {
    QueryResult res = FAILED;

    try {
        byte[] imageBytes = db.getTile(tile.tileX, tile.tileY, tile.zoomLevel);
        if (transparentColor != null || alpha != null) {
            android.graphics.Bitmap bmp = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            if (transparentColor != null) {
                bmp = ImageUtilities.makeTransparent(bmp, transparentColor);
            }
            if (alpha != null) {
                bmp = ImageUtilities.makeBitmapTransparent(bmp, alpha);
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, bos);
            imageBytes = bos.toByteArray();
        }

        Bitmap bitmap = AndroidGraphics.decodeBitmap(new ByteArrayInputStream(imageBytes));

        sink.setTileImage(bitmap);
        res = QueryResult.SUCCESS;
    } catch (Exception e) {
        log.debug("{} Error: {}", tile, e.getMessage());
    } finally {
        sink.completed(res);
    }
}
 
Example 6
Source File: SharedElementSecondAnimationActivity.java    From AndroidDemoProjects with Apache License 2.0 7 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shared_element_second_animation);
    mImageView = (ImageView) findViewById( R.id.image );

    byte[] byteArray = getIntent().getByteArrayExtra("image");
    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    mImageView.setImageBitmap(bitmap);
}
 
Example 7
Source File: BitmapUtils.java    From Android-Application-ZJB with Apache License 2.0 7 votes vote down vote up
/**
     * 根据一张图片的输入流和显示视图的宽高,返回指定宽高的bitmap
     *
     * @param is     原始的图片数据
     * @param width  目标宽度
     * @param height 目标高度
     * @return 指定尺寸的位图
     */
    public static Bitmap createScaledBitmap(InputStream is, int width, int height, Bitmap.Config bitmapConfig) {
        try {
            //1.加到一个byte数组当中
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IoUtils.copyStream(is, bos, null);
            byte[] buffer = bos.toByteArray();
            bos.close();
            is.close();
            //2.计算宽高
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
            float width_ratio = options.outWidth / (float) width;
            float height_ratio = options.outHeight / (float) height;
//            int ratio = (int) (width_ratio > height_ratio ? width_ratio : height_ratio);
            int ratio = calculateInSampleSize(options, width, height);
            //3.decode
            options.inJustDecodeBounds = false;
            options.inPurgeable = true;
            options.inPreferredConfig = bitmapConfig;
            options.inSampleSize = ratio;
            return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }
        return null;
    }
 
Example 8
Source File: XulBitmapUtil.java    From starcor.xul with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * byte[] 转 Bitmap
 */
public static Bitmap bytes2Bitmap(byte[] b) {
    if (b.length == 0) {
        return null;
    }
    return BitmapFactory.decodeByteArray(b, 0, b.length);
}
 
Example 9
Source File: TokenIconCache.java    From bcm-android with GNU General Public License v3.0 7 votes vote down vote up
public Bitmap get(String s) {
    if (cache.get(s) == null)
        return null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = calculateInSampleSize(options, 20, 31);
    return BitmapFactory.decodeByteArray(cache.get(s), 0, cache.get(s).length, options);
}
 
Example 10
Source File: BitmapUtils.java    From DevUtils with Apache License 2.0 7 votes vote down vote up
/**
 * 获取 Bitmap 宽高
 * @param data byte[]
 * @return int[] { 宽度, 高度 }
 */
public static int[] getBitmapWidthHeight(final byte[] data) {
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 只解析图片信息, 不加载到内存中
        options.inJustDecodeBounds = true;
        // 返回的 bitmap 为 null
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        // options.outHeight 为原始图片的高
        return new int[]{options.outWidth, options.outHeight};
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getBitmapWidthHeight");
    }
    return new int[]{0, 0};
}
 
Example 11
Source File: WatchModelImpl.java    From BluetoothCameraAndroid with MIT License 7 votes vote down vote up
@Override
public void onReceivedData(byte[] bytes) {
    final Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    ThreadHandler.getInstance().doInForground(new Runnable() {
        @Override
        public void run() {
            mWatchModelListener.onGotFrameBitmap(image);
        }
    });
}
 
Example 12
Source File: BitmapConvert.java    From DoraemonKit with Apache License 2.0 7 votes vote down vote up
private Bitmap parse(byte[] byteArray) throws OutOfMemoryError {
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap;
    if (maxWidth == 0 && maxHeight == 0) {
        decodeOptions.inPreferredConfig = decodeConfig;
        bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);
    } else {
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        int desiredWidth = getResizedDimension(maxWidth, maxHeight, actualWidth, actualHeight, scaleType);
        int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth, scaleType);

        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, decodeOptions);

        if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }
    return bitmap;
}
 
Example 13
Source File: RxImageTool.java    From RxTools-master with Apache License 2.0 6 votes vote down vote up
/**
 * 按采样大小压缩
 *
 * @param src        源图片
 * @param sampleSize 采样率大小
 * @param recycle    是否回收
 * @return 按采样率压缩后的图片
 */
public static Bitmap compressBySampleSize(Bitmap src, int sampleSize, boolean recycle) {
    if (isEmptyBitmap(src)) return null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = sampleSize;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    src.compress(CompressFormat.JPEG, 100, baos);
    byte[] bytes = baos.toByteArray();
    if (recycle && !src.isRecycled()) src.recycle();
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
 
Example 14
Source File: STUtils.java    From Fatigue-Detection with MIT License 6 votes vote down vote up
@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 {
		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, Bitmap.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;
}
 
Example 15
Source File: BitmapUtils.java    From FastAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * byteArr 转 bitmap
 *
 * @param bytes 字节数组
 * @return bitmap
 */
public static Bitmap bytes2Bitmap(@NonNull byte[] bytes) {
    return (bytes.length == 0) ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
 
Example 16
Source File: ImageRecognizer.java    From react-native-tensorflow with Apache License 2.0 6 votes vote down vote up
private Bitmap loadImage(byte[] image) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}
 
Example 17
Source File: ImageDownload.java    From dynamico with Apache License 2.0 6 votes vote down vote up
public Drawable getDrawable() {
    return new BitmapDrawable(context.getResources(), BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
 
Example 18
Source File: ImageUtilities.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Get an image and thumbnail from a file by its path.
     *
     * @param imageFilePath the image path.
     * @param tryCount      times to try in 300 millis loop, in case the image is
     *                      not yet on disk. (ugly but no other way right now)
     * @return the image and thumbnail data or null.
     */
    public static byte[][] getImageAndThumbnailFromPath(String imageFilePath, int tryCount) throws IOException {
        byte[][] imageAndThumbNail = new byte[2][];

        RandomAccessFile f = new RandomAccessFile(imageFilePath, "r");
        byte[] imageByteArray = new byte[(int) f.length()];
        f.readFully(imageByteArray);

        // first read full image and check existence
        Bitmap image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
//        int count = 0;
//        while (image == null && ++count < tryCount) {
//            try {
//                Thread.sleep(300);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            image = BitmapFactory.decodeFile(imageFilePath);
//        }
//        if (image == null) return null;

        // It is necessary to rotate the image before converting to bytes, as the exif information
        // will be lost afterwards and the image will be incorrectly oriented in some devices
        float orientation = getRotation(imageFilePath);
        if (orientation > 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(orientation);

            image = Bitmap.createBitmap(image, 0, 0, image.getWidth(),
                    image.getHeight(), matrix, true);
        }

        int width = image.getWidth();
        int height = image.getHeight();

        // define sampling for thumbnail
        float sampleSizeF = (float) width / (float) THUMBNAILWIDTH;
        float newHeight = height / sampleSizeF;
        Bitmap thumbnail = Bitmap.createScaledBitmap(image, THUMBNAILWIDTH, (int) newHeight, false);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] thumbnailBytes = stream.toByteArray();

        imageAndThumbNail[0] = imageByteArray;
        imageAndThumbNail[1] = thumbnailBytes;
        return imageAndThumbNail;
    }
 
Example 19
Source File: ImageParser.java    From android-common-utils with Apache License 2.0 6 votes vote down vote up
@Override
public Bitmap decode(DecodeParam param, BitmapFactory.Options options) {
    final byte[] bytes = param.imageArray;
    return BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
}
 
Example 20
Source File: FileUtils.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * decrease iamge size of file to request size
 *
 * @param f image file
 */
public static Bitmap decodeFile(byte[] f) {
    //decode image size
    return BitmapFactory.decodeByteArray(f, 0, f.length);
}