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

3

我有一个字符串文本,想将其保存为图片。目前我有以下代码:

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

然而这并没有创建位图,反而抛出了空指针异常。我该如何将字符串保存到位图中?


这个字符串是位图的代码吗?还是位图应该包含其中的字符串? - Giacomoni
2个回答

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

这很接近,但我得到了一个空位图。 - spacitron
尝试暂时显示画布并查看文本是否正常书写。x和y非常重要,请确保您的文本绘制在设备宽度和高度范围内。 - Viral Patel

1
在Android中,我经常需要将Bitmap转换为String或String转换为Bitmap。当发送或接收Bitmap到服务器并将图像存储在数据库中时。
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;
         }
 }

当我打印StringToBitMap的堆栈跟踪时,我遇到了IllegalArgumentException。它说“错误的base-64”。我试图显示一个数字并将其转换为位图以进行居中处理。我尝试了“0”,但我也尝试了“Hello”和其他几个字符串,仍然出现了错误。 - Peter Griffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接