Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to create a bitmap from a string?

I have some text in a string that I'd like to save as an image. Right now I have the following code:

private void saveImage(View view){
    String mPath = Environment.getExternalStorageDirectory().toString() + "/" + "spacitron.png";  
    String spacitron = "spacitron";
    Bitmap bitmap = BitmapFactory.decodeByteArray(spacitron.getBytes(), 0, spacitron.getBytes().length*5);
    OutputStream fout = null;
    File imageFile = new File(mPath);

    try {
        fout = new FileOutputStream(imageFile);
        //This line throws a null pointer exception
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
        fout.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }

This however does not create the bitmap and instead throws a null pointer exception. How can I save my string to a bitmap?

like image 716
spacitron Avatar asked Feb 03 '26 15:02

spacitron


1 Answers

Create a canvas object and the draw text on the canvas. Then save the canvas as bitmap

Bitmap toDisk = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
canvas.setBitmap(toDisk);


canvas.drawText(message, x , y, paint);

toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/viral.jpg")));
like image 81
AndroidMechanic - Viral Patel Avatar answered Feb 05 '26 05:02

AndroidMechanic - Viral Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!