Android 之 bitmap保存为本地png图片

小咪咪 2023-09-27 17:10 92阅读 0赞

Android 之 把bitmap保存为本地png图片

调用代码

  1. Bitmap bitmap = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);
  2. Canvas canvas = new Canvas(bitmap);
  3. // canvas.drawColor(Color.GREEN);
  4. // paint.setColor(Color.WHITE);
  5. // paint.setTextSize(100);
  6. // Log.e(TAG, "onDrawFrame: frame=" + frame);
  7. // String text = "当前帧数:" + frame++;
  8. // drawTextWithCenterPoint(canvas, 720 / 2, 1280 / 2, text, paint);
  9. // canvas.drawText(text, 0, 100, paint);
  10. //图片保存本地
  11. String fileDir = Environment.getExternalStorageDirectory() + "/111/aaa/";
  12. String fileName = "ksxy-" + System.currentTimeMillis() + ".png";
  13. String path = fileDir + fileName;
  14. if (!new File(fileDir).exists()) {
  15. new File(fileDir).mkdirs();
  16. }
  17. BitmapUtils.bitmap2Path(bitmap, path);

工具类:

  1. import android.graphics.Bitmap;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Paint;
  5. import android.util.Log;
  6. import java.io.FileOutputStream;
  7. import java.io.OutputStream;
  8. public class BitmapUtils {
  9. /**
  10. * 文字生成图片
  11. * @param text
  12. * @param textSize
  13. * @param textColor
  14. * @param bgColor
  15. * @param padding
  16. * @return
  17. */
  18. public static Bitmap text2Bitmap(String text, int textSize, String textColor, String bgColor, int padding) {
  19. Paint paint = new Paint();
  20. paint.setColor(Color.parseColor(textColor));
  21. paint.setTextSize(textSize);
  22. paint.setStyle(Paint.Style.FILL);
  23. paint.setAntiAlias(true);
  24. float width = paint.measureText(text, 0, text.length());
  25. float top = paint.getFontMetrics().top;
  26. float bottom = paint.getFontMetrics().bottom;
  27. Bitmap bm = Bitmap.createBitmap((int) (width + padding * 2), (int) ((bottom - top) + padding * 2), Bitmap.Config.ARGB_8888);
  28. Canvas canvas = new Canvas(bm);
  29. canvas.drawColor(Color.parseColor(bgColor));
  30. canvas.drawText(text, padding, - top + padding, paint);
  31. return bm;
  32. }
  33. /**
  34. * 将bitmap转换为本地的图片
  35. *
  36. * @param bitmap
  37. * @return
  38. */
  39. public static String bitmap2Path(Bitmap bitmap, String path) {
  40. try {
  41. OutputStream os = new FileOutputStream(path);
  42. bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
  43. os.flush();
  44. os.close();
  45. } catch (Exception e) {
  46. Log.e("TAG", "", e);
  47. }
  48. return path;
  49. }
  50. }

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读