【问题标题】:The method write(byte[]) in the type FileOutputStream is not applicable for the arguments (Drawable)FileOutputStream 类型中的 write(byte[]) 方法不适用于参数 (Drawable)
【发布时间】:2012-11-03 17:47:41
【问题描述】:

我试图将我的应用程序资源中的实际图像保存到 SD 卡上的文件中,以便消息传递应用程序可以访问它,但我收到错误 - FileOutputStream 类型中的方法 write(byte[])不适用于参数(可绘制) - 它应该保存它。我相信我没有使用适当的方法来保存实际图像本身,而且我很难找到解决方案。

                        // Selected image id
                int position = data.getExtras().getInt("id");
                ImageAdapter imageAdapter = new ImageAdapter(this);
                ChosenImageView.setImageResource(imageAdapter.mThumbIds[position]);
                Resources res = getResources();
                Drawable drawable = res.getDrawable(imageAdapter.mThumbIds[position]); //(imageAdapter.mThumbIds[position]) is the resource ID
                try {
                    File file = new File(dataFile, FILENAME);
                    file.mkdirs();
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(drawable); // supposed to save the image here, getting the error at fos.write
                    fos.close();
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
              }
            }
        }    

【问题讨论】:

    标签: android image save


    【解决方案1】:

    您的错误确实说明了一切,fileOuputStream 不能采用 Drawable,它需要一个字节数组。

    所以你需要从你的 Drawable 中获取字节。

    尝试:

    Drawable drawable = res.getDrawable(imageAdapter.mThumbIds[position]);
    Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] bitmapdata = stream.toByteArray();
    

    ....

    fos.write(bitmapdata);
    

    当你在做的时候,把fos.close()放在最后的块中

    【讨论】:

    • TYVM 迷失了如何将可绘制对象转换为字节。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多