spacitron
spacitron

Reputation: 2183

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?

Upvotes: 3

Views: 5210

Answers (2)

Viral Patel
Viral Patel

Reputation: 33408

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")));

Upvotes: 3

Kanaiya Katarmal
Kanaiya Katarmal

Reputation: 6108

In Android, I am facing many time convert Bitmap to String and String to Bitmap. When send or receive Bitmap to server and storing Image in database.

Bitmap to String:
public String BitMapToString(Bitmap bitmap){
            ByteArrayOutputStream baos=new  ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
            byte [] arr=baos.toByteArray();
            String result=Base64.encodeToString(arr, Base64.DEFAULT);
            return result;
      }


String to Bitmap:
public Bitmap StringToBitMap(String image){
       try{
           byte [] encodeByte=Base64.decode(image,Base64.DEFAULT);
           Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
           return bitmap;
         }catch(Exception e){
           e.getMessage();
          return null;
         }
 }

Upvotes: 1

Related Questions