我正在将图像转换为字节数组。通过套接字发送它,然后一旦它通过套接字,我需要将它转换回可绘制对象、png 或我可以用作图像按钮背景的任何类型的图像。 问题是,当我转换为字节数组或从数组转换为可绘制对象时,文件已损坏。
我正在从我手机上最后安装的应用程序中获取我的原始图像,如下所示,然后我将它保存到手机上的一个文件中,这样我就可以检查图像文件是否已成功捕获(它是。此时没有任何损坏):
final PackageManager pm = context.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(intent.getData().getSchemeSpecificPart(), 0);
Drawable icon = context.getPackageManager().getApplicationIcon(ai);
BitmapDrawable bitmapIcon = (BitmapDrawable)icon;
FileOutputStream fosIcon = context.openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);
bitmapIcon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = context.openFileInput(applicationName + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// GET FILE DIRECTORY
File imageFile = new File(context.getFilesDir(), applicationName + ".png");
现在我将此位图转换为字节数组以通过套接字发送:
// get bitmap image in bytes to send
int bytes = bitmap.getByteCount();
Log.d("tag_name", "Number of Bytes" + bytes);
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
byte[] array = buffer.array();
Log.d("tag_name", "array" + array);
int start=0;
int len=array.length;
Log.d("tag_name", "length" + len);
new SendToClient(array, applicationName, len, start).execute();
此时我知道我的文件已成功保存为这张图片:
然后,在 SendToClient 中,我使用 DataOutputStream 发送数组。我没有发布这段代码,因为我已经测试过发送数据不是问题发生的地方。如果我不发送字节数组,并在同一 Activity 中从字节数组转换回可绘制对象,它也会损坏。
下面是我在使用 DataInputStream 读取发送的数组后如何从数组转换回可绘制对象:
YuvImage yuvimage=new YuvImage(array, ImageFormat.NV21, 100, 100, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
byte[] jdata = baos.toByteArray();
// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
Log.d("tag_name", "bmp" + bmp);
// convert bitmap to drawable
final Drawable d = new BitmapDrawable(context.getResources(), bmp);
我首先压缩为 JPEG 的原因是因为如果我只使用 BitmapFactory.decodeByteArray,那么我会得到“bmp = null”,首先转换为 JPEG 是我找到的唯一可以获得位图的解决方案'null,但现在我的图像已损坏。这是 Drawable d 的样子:
最佳答案
试试下面的代码,
Convert Bitmap to ByteArray.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.myImage);
ByteArrayOutputStream opstream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, opstream);
byte[] bytArray = opstream.toByteArray();
Convert ByteArray to Bitmap.
Bitmap bitmap = BitmapFactory.decodeByteArray(bytArray, 0, bytArray.length);
ImageView img = (ImageView) findViewById(R.id.imgv1);
img.setImageBitmap(bitmap);
这可能对你有帮助。
关于java - 从字节数组转换为可绘制图像会产生损坏的图像 : Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37080418/