【发布时间】:2018-09-14 21:33:49
【问题描述】:
public Bitmap getResizedBitmap(Bitmap bm, int newWidth) {
int newHeight;
int width = bm.getWidth();
int height = bm.getHeight();
double aspect_ratio = width/height;
newHeight = (int) (newWidth*aspect_ratio);
if(iv!=null){
ViewGroup.LayoutParams params = iv.getLayoutParams();
params.height = newHeight;
iv.setLayoutParams(params);
}
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
Log.e(TAG, "getResizedBitmap: bse64" + getBase64(resizedBitmap) );
return resizedBitmap;
}
在这里,我将位图转换为缩小它。但是在 png 位图应用程序上会崩溃。如果我选择 jpg 文件但选择 png 文件应用程序崩溃,它可以正常工作。 遇到这个错误
致命异常:主要 进程:app.com.imageuploadexample,PID:6984 java.lang.IllegalArgumentException:宽度和高度必须 > 0 在 android.graphics.Bitmap.createBitmap(Bitmap.java:841) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:820) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:751) 在 app.com.imageuploadexample.MainActivity.getResizedBitmap(MainActivity.java:108) 在 app.com.imageuploadexample.MainActivity$1.run(MainActivity.java:75) 在 android.os.Handler.handleCallback(Handler.java:815) 在 android.os.Handler.dispatchMessage(Handler.java:104) 在 android.os.Looper.loop(Looper.java:238) 在 android.app.ActivityThread.main(ActivityThread.java:6016) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:937) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:798)
【问题讨论】:
-
应用程序在转换 png 图像的位图时崩溃您的崩溃日志在哪里
-
您的代码中有一个错误要纠正:'newHeight = (int) (newWidth / aspect_ratio);'。它应该是一个部门。
-
或者你可以传递静态宽度和高度而不是 bm.getWidth() 和 bm.getHeight() 来测试。