下面列出了android.graphics.BitmapRegionDecoder# newInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 由使用者输入一张图片
*/
public void setImage(InputStream is) {
//先读取原图片的信息 高,宽
mOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, mOptions);
mImageWidth = mOptions.outWidth;
mImageHeight = mOptions.outHeight;
//开启复用
mOptions.inMutable = true;
//设置格式成RGB_565
mOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mOptions.inJustDecodeBounds = false;
//创建一个区域解码器
try {
mDecoder = BitmapRegionDecoder.newInstance(is, false);
} catch (IOException e) {
e.printStackTrace();
}
requestLayout();
}
/**
* Reads and crops the bitmap.
* @param outOptions Bitmap options, useful to determine {@code outMimeType}.
*/
private Bitmap crop(BitmapFactory.Options outOptions) throws IOException {
InputStream inputStream = openBitmapInputStream();
// Effeciently crops image without loading full resolution into memory
// https://developer.android.com/reference/android/graphics/BitmapRegionDecoder.html
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(inputStream, false);
try {
Rect rect = new Rect(mX, mY, mX + mWidth, mY + mHeight);
return decoder.decodeRegion(rect, outOptions);
} finally {
if (inputStream != null) {
inputStream.close();
}
decoder.recycle();
}
}
public static BitmapRegionDecoder createBitmapRegionDecoder(
ThreadPool.JobContext jc, byte[] bytes, int offset, int length,
boolean shareable) {
if (offset < 0 || length <= 0 || offset + length > bytes.length) {
throw new IllegalArgumentException(String.format(
"offset = %s, length = %s, bytes = %s",
offset, length, bytes.length));
}
try {
return BitmapRegionDecoder.newInstance(
bytes, offset, length, shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
}
}
@Override
public Point init(Context context, Uri uri) throws Exception {
Log.d(TAG, "Init!");
if (!PartAuthority.isLocalUri(uri)) {
passthrough = new SkiaImageRegionDecoder();
return passthrough.init(context, uri);
}
InputStream inputStream = PartAuthority.getAttachmentStream(context, uri);
this.bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
inputStream.close();
return new Point(bitmapRegionDecoder.getWidth(), bitmapRegionDecoder.getHeight());
}
public static SimpleBitmapRegionDecoderWrapper newInstance(
String pathName, boolean isShareable) {
try {
BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(pathName, isShareable);
if (d != null) {
return new SimpleBitmapRegionDecoderWrapper(d);
}
} catch (IOException e) {
Log.w("BitmapRegionTileSource", "getting decoder failed for path " + pathName, e);
return null;
}
return null;
}
private Bitmap readBitmapInternal(BitmapFactory.Options options, boolean mayUseRegionDecoder,
boolean mayUseWebViewDecoder) {
ImageData imageData = getImageData();
if (imageData.type == ImageType.NOT_IMAGE) {
return null;
}
if (imageData.type != ImageType.IMAGE_SVG) {
Bitmap bitmap = readBitmapSimple(options);
if (bitmap != null) {
return bitmap;
}
if (mayUseRegionDecoder && isRegionDecoderSupported()) {
InputStream input = null;
BitmapRegionDecoder decoder = null;
try {
input = openInputStream();
decoder = BitmapRegionDecoder.newInstance(input, false);
return decoder.decodeRegion(new Rect(0, 0, decoder.getWidth(), decoder.getHeight()), options);
} catch (IOException e) {
Log.persistent().stack(e);
} finally {
IOUtils.close(input);
if (decoder != null) {
decoder.recycle();
}
}
}
}
if (mayUseWebViewDecoder) {
return WebViewBitmapDecoder.loadBitmap(this, options);
}
return null;
}
public static SimpleBitmapRegionDecoderWrapper newInstance(
InputStream is, boolean isShareable) {
try {
BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(is, isShareable);
if (d != null) {
return new SimpleBitmapRegionDecoderWrapper(d);
}
} catch (IOException e) {
Log.w("BitmapRegionTileSource", "getting decoder failed", e);
return null;
}
return null;
}
@TargetApi(Build.VERSION_CODES.N)
private Palette getHotseatPalette() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
if (AndroidVersion.isAtLeastNougat) {
try (ParcelFileDescriptor fd = wallpaperManager
.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)) {
BitmapRegionDecoder decoder = BitmapRegionDecoder
.newInstance(fd.getFileDescriptor(), false);
int height = decoder.getHeight();
Rect decodeRegion = new Rect(0, (int) (height * (1f - HOTSEAT_FRACTION)),
decoder.getWidth(), height);
Bitmap bitmap = decoder.decodeRegion(decodeRegion, null);
decoder.recycle();
if (bitmap != null) {
return Palette.from(bitmap).clearFilters().generate();
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
}
Bitmap wallpaper = ((BitmapDrawable) wallpaperManager.getDrawable()).getBitmap();
return Palette.from(wallpaper)
.setRegion(0, (int) (wallpaper.getHeight() * (1f - HOTSEAT_FRACTION)),
wallpaper.getWidth(), wallpaper.getHeight())
.clearFilters()
.generate();
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_large_image_view);
mImageView = (ImageView) findViewById(R.id.id_imageview);
try
{
InputStream inputStream = getAssets().open("tangyan.jpg");
//获得图片的宽、高
BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
tmpOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, tmpOptions);
int width = tmpOptions.outWidth;
int height = tmpOptions.outHeight;
//设置显示图片的中心区域
BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
mImageView.setImageBitmap(bitmap);
} catch (IOException e)
{
e.printStackTrace();
}
}
public static SimpleBitmapRegionDecoderWrapper newInstance(
InputStream is, boolean isShareable) {
try {
BitmapRegionDecoder d = BitmapRegionDecoder.newInstance(is, isShareable);
if (d != null) {
return new SimpleBitmapRegionDecoderWrapper(d);
}
} catch (IOException e) {
Log.w("BitmapRegionTileSource", "getting decoder failed", e);
return null;
}
return null;
}
public DecoderDrawable(Bitmap scaledBitmap, FileHolder fileHolder) throws IOException {
this.scaledBitmap = scaledBitmap;
if (!fileHolder.isRegionDecoderSupported()) {
throw new IOException("Decoder drawable is not supported");
}
decoder = BitmapRegionDecoder.newInstance(fileHolder.openInputStream(), false);
rotation = fileHolder.getRotation();
width = fileHolder.getImageWidth();
height = fileHolder.getImageHeight();
}
public static BitmapRegionDecoder createBitmapRegionDecoder(
ThreadPool.JobContext jc, FileDescriptor fd, boolean shareable) {
try {
return BitmapRegionDecoder.newInstance(fd, shareable);
} catch (Throwable t) {
Log.w(TAG, t);
return null;
}
}
public static BitmapRegionDecoder createBitmapRegionDecoder(
ThreadPool.JobContext jc, InputStream is, boolean shareable) {
try {
return BitmapRegionDecoder.newInstance(is, shareable);
} catch (Throwable t) {
// We often cancel the creating of bitmap region decoder,
// so just log one line.
Log.w(TAG, "requestCreateBitmapRegionDecoder: " + t);
return null;
}
}
@Override
public Point init(Context context, Uri uri) throws Exception {
Log.w(TAG, "Init!");
if (!PartAuthority.isLocalUri(uri)) {
passthrough = new SkiaImageRegionDecoder();
return passthrough.init(context, uri);
}
InputStream inputStream = PartAuthority.getAttachmentStream(context, uri);
this.bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
inputStream.close();
return new Point(bitmapRegionDecoder.getWidth(), bitmapRegionDecoder.getHeight());
}
private Bitmap createClippedBitmap() {
//if (mSampleSize <= 1) {
// TODO has problem, this method is not useful on some picture
// return mClipImageView.clip();
//}
final float[] matrixValues = mClipImageView.getClipMatrixValues();
final float scale = matrixValues[Matrix.MSCALE_X];
final float transX = matrixValues[Matrix.MTRANS_X];
final float transY = matrixValues[Matrix.MTRANS_Y];
final Rect border = mClipImageView.getClipBorder();
final float cropX = ((-transX + border.left) / scale) * mSampleSize;
final float cropY = ((-transY + border.top) / scale) * mSampleSize;
final float cropWidth = (border.width() / scale) * mSampleSize;
final float cropHeight = (border.height() / scale) * mSampleSize;
final RectF srcRect = new RectF(cropX, cropY, cropX + cropWidth, cropY + cropHeight);
final Rect clipRect = getRealRect(srcRect);
final BitmapFactory.Options ops = new BitmapFactory.Options();
final Matrix outputMatrix = new Matrix();
outputMatrix.setRotate(mDegree);
if (mMaxWidth > 0 && cropWidth > mMaxWidth) {
ops.inSampleSize = findBestSample((int) cropWidth, mMaxWidth);
final float outputScale = mMaxWidth / (cropWidth / ops.inSampleSize);
outputMatrix.postScale(outputScale, outputScale);
}
BitmapRegionDecoder decoder = null;
try {
decoder = BitmapRegionDecoder.newInstance(mInput, false);
final Bitmap source = decoder.decodeRegion(clipRect, ops);
recycleImageViewBitmap();
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
outputMatrix, false);
} catch (Exception e) {
return mClipImageView.clip();
} finally {
if (decoder != null && !decoder.isRecycled()) {
decoder.recycle();
}
}
}
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws Exception {
String uriString = uri.toString();
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List<String> segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
decoder = BitmapRegionDecoder.newInstance(
context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM),
false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(
uriString.substring(FILE_PREFIX.length()),
false);
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
decoder = BitmapRegionDecoder.newInstance(inputStream, false);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) { /* Ignore */ }
}
}
}
return new Point(decoder.getWidth(), decoder.getHeight());
}
/**
* Takes an inputstream, loads a bitmap optimized of space and then crops it for the view.
* @param iStream Inputstream to the image.
* @param containerHeight Height of the image holder container.
* @param containerWidth Width of the image holder container.
* @return Cropped/masked bitmap.
*/
public static Bitmap loadMaskedBitmap(InputStream iStream, int containerHeight, int containerWidth){
// Load image data before loading the image itself.
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(iStream,null,bmOptions);
int photoH = bmOptions.outHeight;
int photoW = bmOptions.outWidth;
// Find a suitable scalefactor to load the smaller bitmap, and then set the options.
int scaleFactor = Math.min(photoH/containerHeight, photoW/containerHeight);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
// Load the square region out of the bitmap.
Bitmap bmap=null;
BitmapRegionDecoder decoder;
try {
iStream.reset();
decoder = BitmapRegionDecoder.newInstance(iStream, false);
bmap = decoder.decodeRegion(new Rect(0, 0, Math.min(photoH, photoW), Math.min(photoH, photoW)),bmOptions);
} catch (IOException e) {
e.printStackTrace();
}
// Calculate new width of the bitmap based on the width of the container
int bitmapNewWidth = (bmap.getWidth()*containerWidth)/containerHeight;
// Produce clipping mask on the canvas and draw the bitmap
Bitmap targetBitmap = Bitmap.createBitmap(bitmapNewWidth, bmap.getHeight(), bmap.getConfig());
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(bmap.getWidth() / 2, bmap.getHeight() / 2, bmap.getWidth() / 2, Path.Direction.CCW);
canvas.clipPath(path);
canvas.drawBitmap(bmap, 0, 0, null);
// Retrieve the clipped bitmap and return
return targetBitmap;
}
@Override
public Point init(Context context, Uri uri) throws Exception {
String uriString = uri.toString();
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List<String> segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
decoder = BitmapRegionDecoder.newInstance(inputStream, false);
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
}
}
}
return new Point(decoder.getWidth(), decoder.getHeight());
}
@Override
public Point init(Context context, Uri uri) throws Exception {
String uriString = uri.toString();
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List<String> segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
} else {
InputStream inputStream = null;
try {
ContentResolver contentResolver = context.getContentResolver();
inputStream = contentResolver.openInputStream(uri);
decoder = BitmapRegionDecoder.newInstance(inputStream, false);
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (Exception e) { }
}
}
}
return new Point(decoder.getWidth(), decoder.getHeight());
}
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws IOException, PackageManager.NameNotFoundException {
String uriString = uri.toString();
if (uriString.startsWith(RESOURCE_PREFIX)) {
Resources res;
String packageName = uri.getAuthority();
if (context.getPackageName().equals(packageName)) {
res = context.getResources();
} else {
PackageManager pm = context.getPackageManager();
res = pm.getResourcesForApplication(packageName);
}
int id = 0;
List<String> segments = uri.getPathSegments();
int size = segments.size();
if (size == 2 && segments.get(0).equals("drawable")) {
String resName = segments.get(1);
id = res.getIdentifier(resName, "drawable", packageName);
} else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
try {
id = Integer.parseInt(segments.get(0));
} catch (NumberFormatException ignored) {
}
}
decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
} else if (uriString.startsWith(ASSET_PREFIX)) {
String assetName = uriString.substring(ASSET_PREFIX.length());
decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
} else if (uriString.startsWith(FILE_PREFIX)) {
decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
} else {
try (InputStream input = context.getContentResolver().openInputStream(uri)) {
if (input == null)
throw new RuntimeException("Content resolver returned null stream. Unable to initialise with uri.");
decoder = BitmapRegionDecoder.newInstance(input, false);
}
}
if (decoder != null && !decoder.isRecycled()) return new Point(decoder.getWidth(), decoder.getHeight());
else return new Point(-1, -1);
}