我正在将图像转换为字节数组,通过套接字发送它,然后一旦通过套接字,我需要将其转换回可绘制的、png格式或任何可以用作图像按钮背景的图像类型。问题是,无论我是将其转换为字节数组还是从数组转换为可绘制的图像时,文件都会损坏。
我按照以下步骤从手机上安装的最后一个应用程序中获取原始图像,然后将其保存到手机上的文件中,以便在此时检查图像文件是否已成功捕获(这样做了,此时没有任何损坏):
现在我正在将这个位图转换为字节数组以通过套接字发送:
我先将图像压缩为JPEG格式的原因是,如果我仅使用 BitmapFactory.decodeByteArray,则会得到 "bmp = null" 的结果。先转换为JPEG是我找到的唯一解决方案,可以获取不为空的位图,但现在我的图像已经损坏了。以下是 Drawable d 的样子:
我按照以下步骤从手机上安装的最后一个应用程序中获取原始图像,然后将其保存到手机上的文件中,以便在此时检查图像文件是否已成功捕获(这样做了,此时没有任何损坏):
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发送数组。我不会贴出此代码,因为我已经测试过发送数据不是问题发生的地方。如果我不发送字节数组,并在同一活动中将其从字节数组转换回可绘制对象,则其也会损坏。
以下是我如何在使用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是我找到的唯一解决方案,可以获取不为空的位图,但现在我的图像已经损坏了。以下是 Drawable d 的样子: