【问题标题】:Android: how to create a bitmap from a string?Android:如何从字符串创建位图?
【发布时间】:2014-03-20 11:53:41
【问题描述】:

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

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

但是,这不会创建位图,而是会引发空指针异常。如何将我的字符串保存到位图?

【问题讨论】:

  • 是字符串,位图的代码吗?或者位图应该是一个包含字符串的位图?

标签: java android bitmap


【解决方案1】:

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

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

【讨论】:

  • 很接近但我得到一个空白位图。
  • 尝试暂时显示你的画布,看看它是否写得很好。 x 和 y 非常重要。确保您的文字在您设备的宽度和高度范围内绘制。
【解决方案2】:

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

【讨论】:

  • 我在打印 StringToBitMap 的堆栈轨迹时遇到 IllegalArgumentException。它说“bad base-64”。我正在尝试显示一个数字并将其转换为位图以用于居中目的。我尝试了“0”,但我也尝试了“Hello”和其他几个字符串,但它仍然给了我这个错误。
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多