我在尝试压缩位图时遇到空指针异常,因此我可以将其发送到ByteArrayOutputStream以获取字节数组。日志错误如下所示。
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at worldnp.zpmobi.mobi.test.MainActivity$Encode_image.doInBackground(MainActivity.java:102)
at worldnp.zpmobi.mobi.test.MainActivity$Encode_image.doInBackground(MainActivity.java:94)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
java代码:
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(file_uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
当应该压缩位图时,应用程序崩溃了。我的代码在哪里做错了?
答案 0 :(得分:1)
protected Void doInBackground(Void... voids) {
Bitmap bitmap = BitmapFactory.decodeFile(file_uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
初始化时,您没有为变量bitmap
提供类型。