Java Code Examples for android.graphics.BitmapFactory.decodeStream()

The following are Jave code examples for showing how to use decodeStream() of the android.graphics.BitmapFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Zxing   File: CaptureActivity.java   View Source Code Vote up 6 votes
protected Result scanningImage(Uri path) {
    if (path == null || path.equals("")) {
        return null;
    }
    // DecodeHintType 和EncodeHintType
    Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
    hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 设置二维码内容的编码
    try {
        Bitmap scanBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        return reader.decode(bitmap1, hints);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 2
Project: boohee_v5.6   File: BaseImageDecoder.java   View Source Code Vote up 6 votes
protected ImageFileInfo defineImageSizeAndRotation(InputStream imageStream, ImageDecodingInfo
        decodingInfo) throws IOException {
    ExifInfo exif;
    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(imageStream, null, options);
    String imageUri = decodingInfo.getImageUri();
    if (decodingInfo.shouldConsiderExifParams() && canDefineExifParams(imageUri, options
            .outMimeType)) {
        exif = defineExifOrientation(imageUri);
    } else {
        exif = new ExifInfo();
    }
    return new ImageFileInfo(new ImageSize(options.outWidth, options.outHeight, exif
            .rotation), exif);
}
 
Example 3
Project: Accessibility   File: BitmapUtils.java   View Source Code Vote up 6 votes
public static boolean verifyBitmap(InputStream input) {
    if (input == null) {
        return false;
    }
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    input = input instanceof BufferedInputStream ? input
            : new BufferedInputStream(input);
    BitmapFactory.decodeStream(input, null, options);
    try {
        input.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return (options.outHeight > 0) && (options.outWidth > 0);
}
 
Example 4
Project: andcouchbaseentity   File: ImageUtil.java   View Source Code Vote up 6 votes
/**
 * Decode and sample down a bitmap from an input stream to the requested width and height.
 *
 * @param is The input stream to read from
 * @param reqWidth The requested width of the resulting bitmap
 * @param reqHeight The requested height of the resulting bitmap
 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions
 *         that are equal to or greater than the requested width and height
 */
public static Bitmap decodeBitmapFromInputStream(InputStream is, int reqWidth, int reqHeight) {
    // Bitmap m = BitmapFactory.decodeStream(is);
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, options);

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

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

    Bitmap mm = BitmapFactory.decodeStream(is, null, options);

    return mm;
}
 
Example 5
Project: RxReview   File: BitmapUtil.java   View Source Code Vote up 5 votes
public static Bitmap getBitmapFromAsset(Context context, String filePath) {
    AssetManager assetManager = context.getAssets();

    InputStream istr;
    Bitmap bitmap = null;
    try {
        istr = assetManager.open(filePath);
        bitmap = BitmapFactory.decodeStream(istr);
    } catch (IOException e) {
        // handle exception
    }

    return bitmap;
}
 
Example 6
Project: stynico   File: ImageUtils.java   View Source Code Vote up 5 votes
/**
 * 根据InputStream获取图片实际的宽度和高度
 *
 * @param imageStream
 * @return
 */
public static ImageSize getImageSize(InputStream imageStream) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(imageStream, null, options);
    return new ImageSize(options.outWidth, options.outHeight);
}
 
Example 7
Project: cniao5   File: ImageUtils.java   View Source Code Vote up 5 votes
/**
 * 根据InputStream获取图片实际的宽度和高度
 *
 * @param imageStream
 * @return
 */
public static ImageSize getImageSize(InputStream imageStream)
{
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(imageStream, null, options);
    return new ImageSize(options.outWidth, options.outHeight);
}
 
Example 8
Project: GravityBox   File: AppPickerPreference.java   View Source Code Vote up 5 votes
private AppInfo getAppInfoFromValue(String value) {
    AppInfo appInfo = new AppInfo();
    if (value == null) return appInfo;

    try {
        Intent intent = Intent.parseUri(value, 0);

        int iconResId = intent.getStringExtra("iconResName") != null ?
                mResources.getIdentifier(intent.getStringExtra("iconResName"),
                        "drawable", mContext.getPackageName()) : 0;
        if (iconResId != 0) {
            appInfo.icon = mResources.getDrawable(iconResId);
        } else if (intent.hasExtra("icon")) {
            final String appIconPath = intent.getStringExtra("icon");
            if (appIconPath != null) {
                File f = new File(appIconPath);
                if (f.exists() && f.canRead()) {
                    FileInputStream fis = new FileInputStream(f);
                    appInfo.icon = new BitmapDrawable(mResources, BitmapFactory.decodeStream(fis));
                    fis.close();
                }
            }
        }

        int mode = intent.getIntExtra("mode", MODE_APP);
        if (mode == MODE_APP) {
            ComponentName cn = intent.getComponent();
            ActivityInfo ai = mPackageManager.getActivityInfo(cn, 0);
            appInfo.name = (ai.loadLabel(mPackageManager).toString());
            if (appInfo.icon == null) {
                appInfo.icon = ai.loadIcon(mPackageManager);
            }
        } else if (mode == MODE_SHORTCUT) {
            appInfo.name = intent.getStringExtra("prefLabel");
        }
        return appInfo;
    } catch (Exception e) {
        e.printStackTrace();
        return appInfo;
    }
}
 
Example 9
Project: sctalk   File: FileUtil.java   View Source Code Vote up 5 votes
@SuppressWarnings("unused")
private static Bitmap getBitmap(InputStream fs) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 1;
    Bitmap imgBitmap = BitmapFactory.decodeStream(fs, null, opts);
    if (imgBitmap != null) {
        int width = imgBitmap.getWidth();
        int height = imgBitmap.getHeight();
        imgBitmap = Bitmap.createScaledBitmap(imgBitmap, width, height,
                true);
    }
    return imgBitmap;
}
 
Example 10
Project: GrowingProject   File: AssetUtils.java   View Source Code Vote up 5 votes
private static Bitmap readBitmap(InputStream pInputStream) {
    if (pInputStream == null) {
        return null;
    }
    try {
        return BitmapFactory.decodeStream(pInputStream);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        close(pInputStream);
    }
}
 
Example 11
Project: Camera-Roll-Android-App   File: Util.java   View Source Code Vote up 5 votes
public static int[] getImageDimensions(Context context, Uri uri) {
    int[] dimensions = new int[]{0, 0};

    try {
        InputStream is = context.getContentResolver().openInputStream(uri);

        //try exif
        String mimeType = MediaType.getMimeType(context, uri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                && MediaType.doesSupportExifMimeType(mimeType)
                && is != null) {
            ExifInterface exif = new ExifInterface(is);
            if (exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH) != null
                    && exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH) != null) {
                int width = (int) ExifUtil.getCastValue(exif, ExifInterface.TAG_IMAGE_WIDTH);
                int height = (int) ExifUtil.getCastValue(exif, ExifInterface.TAG_IMAGE_LENGTH);
                if (width != 0 && height != 0) {
                    return new int[]{width, height};
                }
            }
        }

        //exif didn't work
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, new Rect(0, 0, 0, 0), options);
        dimensions[0] = options.outWidth;
        dimensions[1] = options.outHeight;

        if (is != null) {
            is.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return dimensions;
}
 
Example 12
Project: AndroidBasicLibs   File: ImageUtils.java   View Source Code Vote up 5 votes
public static Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) {
        options -= 10;
        if (options > 0) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    return BitmapFactory.decodeStream(isBm, null, null);
}
 
Example 13
Project: boohee_v5.6   File: AuthAgent.java   View Source Code Vote up 5 votes
private Drawable a(String str, Context context) {
    IOException e;
    Drawable createFromStream;
    try {
        InputStream open = context.getApplicationContext().getAssets().open(str);
        if (open == null) {
            return null;
        }
        if (str.endsWith(".9.png")) {
            Bitmap decodeStream = BitmapFactory.decodeStream(open);
            if (decodeStream == null) {
                return null;
            }
            byte[] ninePatchChunk = decodeStream.getNinePatchChunk();
            NinePatch.isNinePatchChunk(ninePatchChunk);
            return new NinePatchDrawable(decodeStream, ninePatchChunk, new Rect(), null);
        }
        createFromStream = Drawable.createFromStream(open, str);
        try {
            open.close();
            return createFromStream;
        } catch (IOException e2) {
            e = e2;
            e.printStackTrace();
            return createFromStream;
        }
    } catch (IOException e3) {
        IOException iOException = e3;
        createFromStream = null;
        e = iOException;
        e.printStackTrace();
        return createFromStream;
    }
}
 
Example 14
Project: studydemo   File: UtilTools.java   View Source Code Vote up 5 votes
public static void getImageToShare(Context mContext, ImageView imageView) {
    //1.拿到string
    String imgString = ShareUtil.getString(mContext, "image_title", "");
    if (!imgString.equals("")) {
        //2.利用Base64将我们string转换
        byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
        ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
        //3.生成bitmap
        Bitmap bitmap = BitmapFactory.decodeStream(byStream);
        imageView.setImageBitmap(bitmap);
    }
}
 
Example 15
Project: Loyalty   File: CacheManager.java   View Source Code Vote up 5 votes
public Bitmap restoreFromCache(Card card, Cache cache) throws IOException {
    String fileName = cache.getCacheLocation(getFileName(card));
    FileInputStream in = context.openFileInput(fileName);
    Bitmap out = BitmapFactory.decodeStream(in);
    in.close();
    return out;
}
 
Example 16
Project: AnchorImageView   File: TestUtils.java   View Source Code Vote up 5 votes
static Bitmap getAnchorImage(Context context) {
    try {
        InputStream anchorIS = context.getAssets().open("anchor_test.png");
        return BitmapFactory.decodeStream(anchorIS);
    } catch (Exception e) {//IO
        return null;
    }
}
 
Example 17
Project: GitHub   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
protected ImageFileInfo defineImageSizeAndRotation(InputStream imageStream, ImageDecodingInfo decodingInfo)
		throws IOException {
	Options options = new Options();
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeStream(imageStream, null, options);

	ExifInfo exif;
	String imageUri = decodingInfo.getImageUri();
	if (decodingInfo.shouldConsiderExifParams() && canDefineExifParams(imageUri, options.outMimeType)) {
		exif = defineExifOrientation(imageUri);
	} else {
		exif = new ExifInfo();
	}
	return new ImageFileInfo(new ImageSize(options.outWidth, options.outHeight, exif.rotation), exif);
}
 
Example 18
Project: GifImageLoader   File: BaseImageDecoder.java   View Source Code Vote up 5 votes
/**
 * Decodes image from URI into {@link Bitmap}. Image is scaled close to incoming {@linkplain ImageSize target size}
 * during decoding (depend on incoming parameters).
 *
 * @param decodingInfo Needed data for decoding image
 * @return Decoded bitmap
 * @throws IOException                   if some I/O exception occurs during image reading
 * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol)
 */
@Override
public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
	Bitmap decodedBitmap;
	ImageFileInfo imageInfo;

	InputStream imageStream = getImageStream(decodingInfo);
	if (imageStream == null) {
		L.e(ERROR_NO_IMAGE_STREAM, decodingInfo.getImageKey());
		return null;
	}
	try {
		imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
		imageStream = resetStream(imageStream, decodingInfo);
		Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
		decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
	} finally {
		IoUtils.closeSilently(imageStream);
	}

	if (decodedBitmap == null) {
		L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
	} else {
		decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation,
				imageInfo.exif.flipHorizontal);
	}
	return decodedBitmap;
}
 
Example 19
Project: GitHub   File: BitmapHunter.java   View Source Code Vote up 4 votes
/**
 * Decode a byte stream into a Bitmap. This method will take into account additional information
 * about the supplied request in order to do the decoding efficiently (such as through leveraging
 * {@code inSampleSize}).
 */
static Bitmap decodeStream(Source source, Request request) throws IOException {
  BufferedSource bufferedSource = Okio.buffer(source);

  boolean isWebPFile = Utils.isWebPFile(bufferedSource);
  boolean isPurgeable = request.purgeable && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP;
  BitmapFactory.Options options = RequestHandler.createBitmapOptions(request);
  boolean calculateSize = RequestHandler.requiresInSampleSize(options);

  // We decode from a byte array because, a) when decoding a WebP network stream, BitmapFactory
  // throws a JNI Exception, so we workaround by decoding a byte array, or b) user requested
  // purgeable, which only affects bitmaps decoded from byte arrays.
  if (isWebPFile || isPurgeable) {
    byte[] bytes = bufferedSource.readByteArray();
    if (calculateSize) {
      BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
      RequestHandler.calculateInSampleSize(request.targetWidth, request.targetHeight, options,
          request);
    }
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
  } else {
    InputStream stream = bufferedSource.inputStream();
    if (calculateSize) {
      // TODO use an InputStream that buffers with Okio...
      MarkableInputStream markStream = new MarkableInputStream(stream);
      stream = markStream;
      markStream.allowMarksToExpire(false);
      long mark = markStream.savePosition(1024);
      BitmapFactory.decodeStream(stream, null, options);
      RequestHandler.calculateInSampleSize(request.targetWidth, request.targetHeight, options,
          request);
      markStream.reset(mark);
      markStream.allowMarksToExpire(true);
    }
    Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
    if (bitmap == null) {
      // Treat null as an IO exception, we will eventually retry.
      throw new IOException("Failed to decode stream.");
    }
    return bitmap;
  }
}
 
Example 20
Project: letv   File: LetvWeixinShare.java   View Source Code Vote up 4 votes
public static Bitmap returnBitMap(String url) {
    URL url2;
    MalformedURLException e;
    IOException e2;
    Bitmap bitmap = null;
    InputStream is = null;
    if (shareMode == 4) {
        shareMode = -1;
        if (!(TextUtils.isEmpty(url) || url.contains(IDataSource.SCHEME_HTTP_TAG))) {
            try {
                bitmap = FileUtils.getBitmapByPath(url, LeMessageIds.MSG_ALBUM_HALF_FETCH_EXPEND_VIEWPAGER_LAYOUT, LeMessageIds.MSG_ALBUM_HALF_FETCH_EXPEND_VIEWPAGER_LAYOUT);
            } catch (FileNotFoundException e3) {
                e3.printStackTrace();
            }
        }
    } else {
        try {
            URL myFileUrl = new URL(url);
            try {
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
                url2 = myFileUrl;
            } catch (MalformedURLException e4) {
                e = e4;
                url2 = myFileUrl;
                e.printStackTrace();
                LogInfo.log("fornia", "addparam bitmap:" + bitmap);
                return bitmap;
            } catch (IOException e5) {
                e2 = e5;
                url2 = myFileUrl;
                e2.printStackTrace();
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                LogInfo.log("fornia", "addparam bitmap:" + bitmap);
                return bitmap;
            }
        } catch (MalformedURLException e6) {
            e = e6;
            e.printStackTrace();
            LogInfo.log("fornia", "addparam bitmap:" + bitmap);
            return bitmap;
        } catch (IOException e7) {
            e2 = e7;
            e2.printStackTrace();
            if (is != null) {
                is.close();
            }
            LogInfo.log("fornia", "addparam bitmap:" + bitmap);
            return bitmap;
        }
    }
    LogInfo.log("fornia", "addparam bitmap:" + bitmap);
    return bitmap;
}