【问题标题】:creating .bmp image file from Bitmap class从 Bitmap 类创建 .bmp 图像文件
【发布时间】:2013-09-06 06:48:06
【问题描述】:

我创建了一个使用套接字的应用程序,客户端在该套接字中接收图像并将图像的数据存储在 Bitmap 类中......

谁能告诉我如何从这个位图对象创建一个名为 myimage.pngmyimage.bmp 的文件

String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decode(base64Code);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);

【问题讨论】:

    标签: java android bitmap png bmp


    【解决方案1】:

    尝试以下代码将图像保存为 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);
    

    【讨论】:

    • 当我尝试这个时------------FileOutputStream out = new FileOutputStream("Image.png"); bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);------------我得到 -------- ------java.io.FileNotFoundException:/Image.png:打开失败:EROFS(只读文件系统)
    • @user2318483,你可以像下面这样使用。 String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "your_file.png";
    • 先生,当我发送 50KB 400X400 等大图像文件时,我收到 java.nio.BufferOverflowException
    • @user2318483,您在模拟器中进行测试吗?
    • @user2318483,我尝试使用 1600 * 1200 分辨率和 1.3 MB 大小的图像。我在实际设备中进行了测试,没有得到这样的异常。如果您在其中运行,我认为这是由于模拟器的内存不足.. :)
    【解决方案2】:
    try {
       FileOutputStream out = new FileOutputStream(filename);
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
       out.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2020-10-23
      • 2022-01-02
      相关资源
      最近更新 更多