如何在Android中将图像转换成字节数组
我面临一个真正的问题。我需要将图像转换为字节数组格式,以便将字节数组上载到web服务器。我试了很多,但都不管用。我还得到了字节数组的负值。我不确定我在数组中获取字节值时做错了什么 下面是我的代码。请帮帮我,我做错了什么如何在Android中将图像转换成字节数组,android,bitmap,Android,Bitmap,我面临一个真正的问题。我需要将图像转换为字节数组格式,以便将字节数组上载到web服务器。我试了很多,但都不管用。我还得到了字节数组的负值。我不确定我在数组中获取字节值时做错了什么 下面是我的代码。请帮帮我,我做错了什么 Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home_menu_icon); ByteArrayOutputStream bos = new ByteArrayOutputStream(
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home_menu_icon);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
如果您的图像来自画廊和照相机,我将在这里显示这两种图像的代码
if (requestCode == IMAGE_PICKER_REQUEST && resultCode == RESULT_OK) {
fileName = getRealPathFromURI(data.getData());
try {
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
image.setImageBitmap(bitmap);
//picNameText.setText("Selected: en"
// + getStringNameFromRealPath(fileName));
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream1);
imageInByte = stream1.toByteArray();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == IMAGE_TAKER_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo);
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream2);
imageInByte = stream2.toByteArray();
}
享受为我工作的乐趣…尝试以下代码
int bytes = bitmap.getByteCount();
//Create a new buffer
ByteBuffer buffer = ByteBuffer.allocate(bytes);
//Move the byte data to the buffer
b.copyPixelsToBuffer(buffer);
byte[] array = buffer.array();
Bitmap.setPixels()
将位图转换为int数组和vise
韵文一个int数组可以很容易地转换成字节数组Bitmap.copyPixelsToBuffer()
展示了一个很好的解决方案,与第一个几乎相同32位位图使用int32保存ARGB颜色,我们可以使用int数组表示位图。使用Bitmap.getPixels()和Bitmap.setPixels()将位图转换为int数组和vise verse。int数组可以很容易地转换为字节数组。不要转换为base64。。。如果您关心质量,请尝试压缩为PNG格式,因为JPEG是最差的格式:
bmp.compress(Bitmap.CompressFormat.PNG,100,bos)代码>否则代码似乎没问题。原语是用Java签名的这一事实无关紧要——一个字节仅仅是8位,是否将其解释为签名范围取决于您自己。“这是有符号的”或“这是无符号的”没有神奇的标志。检查这里你的问题没有解决吗?