从Bitmap类创建.bmp图像文件

3
我创建了一个使用套接字的应用程序,在其中客户端接收图像并将图像数据存储在 Bitmap 类中。
请问有人可以告诉我如何从这个 Bitmap 对象创建一个名为 myimage.png 或 myimage.bmp 的文件吗?
String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decode(base64Code);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
2个回答

5
尝试以下代码以将图像保存为PNG格式:
try {
   FileOutputStream out = new FileOutputStream(filename);
   bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
   e.printStackTrace();
}
out.flush();
out.close();

这里的100代表压缩保存的质量。你可以在0到100之间选择任何数字。数字越小,质量越差,文件大小也会减小。

注意

你需要在Android Manifest文件中获取权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

编辑

要将您的图片保存为.BMP格式,Android Bitmap Util 将会对您有所帮助。它具有非常简单的实现方式。

String sdcardBmpPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sample_text.bmp";
Bitmap testBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_text);
AndroidBmpUtil bmpUtil = new AndroidBmpUtil();
boolean isSaveResult = bmpUtil.save(testBitmap, sdcardBmpPath);

1
先生,当我发送如50KB 400X400这样的大图像文件时,我会得到java.nio.BufferOverflowException异常。 - user2318483
@user2318483,你是在模拟器上进行测试吗? - Chintan Rathod
@user2318483,我尝试使用1600 * 1200分辨率和1.3 MB大小的图像。我在实际设备上进行了测试,并没有出现这样的异常。我认为如果您在模拟器中运行,这是由于内存不足造成的.. :) - Chintan Rathod
先生,我没有在模拟器中运行Android......但是在连接到我的电脑上的Android平板电脑上运行。 - user2318483
@user2318483,好的,请尝试使用BufferedOutputStream bos = new BufferedOutputStream(out);bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);代码。 - Chintan Rathod
显示剩余8条评论

0
try {
   FileOutputStream out = new FileOutputStream(filename);
   bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
   e.printStackTrace();
} finally {
   out.close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接