Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saved Bitmap is black

I created a bitmap with text and I can view it in an Imageview, but when I save the Bitmap I only get a black image. I have spend three hours looking at similar questions but none of the worked for me. Here is the code. Thanks for any help.

 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();
    }

}
like image 936
Kim HJ Avatar asked Jan 19 '15 06:01

Kim HJ


1 Answers

JPEG Image has a black background by default, so if your text color is also black you will get a black image. If your image has no background color, you must save it as PNG. Change as following and have a try:

LabelBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

to:

LabelBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
like image 157
Lei Guo Avatar answered Oct 10 '22 04:10

Lei Guo