保存的位图是黑色的

Kim*_* HJ 3 file-io android bitmap

我用文本创建了一个位图,我可以在Imageview中查看它,但是当我保存位图时,我只得到一个黑色图像.我花了三个小时看类似的问题,但没有一个对我有用.这是代码.谢谢你的帮助.

 public void createBitmap(){
    Bitmap LabelBitmap;
    FileOutputStream fos = null;
//create Text Bitmap
    LabelBitmap = textAsBitmap(this,"BRO D 0813","fonts/arialbd.ttf", 4, Color.BLACK);
//load bitmap in to Imageview
    ImageView myImageView = (ImageView) findViewById(R.id.imageView);
    myImageView.setImageBitmap(LabelBitmap);
// save bitmap
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/myfolder");
    myDir.mkdirs();

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    LabelBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    if (!myDir.exists()) {
        myDir.mkdir();
    }

    File myDirFile = new File(root +"/myfolder/mybitmap.jpg");

    try {
        if(myDirFile.exists()){
            myDirFile.delete();
        }
        myDirFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        fos = new FileOutputStream(myDirFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fos.write(bytes.toByteArray());
        fos.flush();
        fos.close();
        Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)

Lei*_*Guo 8

JPEG默认情况下,图像的背景为黑色,因此如果文本颜色为黑色,则会显示黑色图像.如果您的图像没有背景颜色,则必须将其另存为PNG.更改如下并尝试:

LabelBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Run Code Online (Sandbox Code Playgroud)

至:

LabelBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
Run Code Online (Sandbox Code Playgroud)