Android:如何从字符串创建位图?

时间:2014-03-20 11:53:41

标签: java android bitmap

我在字符串中有一些文字,我想将其保存为图像。现在我有以下代码:

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) {
        }
    }

然而,这不会创建位图,而是抛出空指针异常。如何将字符串保存到位图?

2 个答案:

答案 0 :(得分:3)

在画布上创建画布对象和绘图文本。然后将画布保存为位图

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

答案 1 :(得分:1)

在Android中,我面临很多时候将Bitmap转换为String和String转换为Bitmap。向服务器发送或接收Bitmap并将Image存储在数据库中时。

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