我想将字符串中的一些文本另存为图像。现在我有以下代码:
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) {
}
}
但这并没有创建位图,而是抛出了一个空指针异常。如何将字符串保存为位图?
最佳答案
创建 Canvas 对象并在 Canvas 上绘制文本。然后将 Canvas 保存为位图
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")));
关于java - Android:如何从字符串创建位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22532136/