Android 将bitmap保存为本地png图片

作者: android 发布时间: 2021-02-25 浏览: 575 次 编辑

Android 将bitmap保存为本地png图片,

废话补多少直接上代码:

BItmapUtils:

package com.zhangyu.myopengl.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class BitmapUtils {


    /**
     * 将bitmap转换为本地的图片
     *
     * @param bitmap
     * @return
     */
    public static String bitmap2Path(Bitmap bitmap, String path) {
        try {
            OutputStream os = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e("TAG", "", e);
        }
        return path;
    }


    /**
     * 文字生成图片
     * @param text
     * @param textSize
     * @param textColor
     * @param bgColor
     * @param padding
     * @return
     */
    public static Bitmap text2Bitmap(String text, int textSize, String textColor, String bgColor, int padding) {

        Paint paint = new Paint();
        paint.setColor(Color.parseColor(textColor));
        paint.setTextSize(textSize);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);

        float width = paint.measureText(text, 0, text.length());

        float top = paint.getFontMetrics().top;
        float bottom = paint.getFontMetrics().bottom;

        Bitmap bm = Bitmap.createBitmap((int) (width + padding * 2), (int) ((bottom - top) + padding * 2), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);

        canvas.drawColor(Color.parseColor(bgColor));
        canvas.drawText(text, padding, - top + padding, paint);
        return bm;
    }

}

Main里面使用:

        Bitmap bitmap = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.GREEN);
        paint.setColor(Color.WHITE);
        paint.setTextSize(100);
        Log.e(TAG, "onDrawFrame: frame=" + frame);
        String text = "当前帧数:" + frame++;
        drawTextWithCenterPoint(canvas, 720 / 2, 1280 / 2, text, paint);
        canvas.drawText(text, 0, 100, paint);
        //图片保存本地
        String fileDir = Environment.getExternalStorageDirectory() + "/1/pic/";
        String fileName = System.currentTimeMillis() + ".png";
        String path = fileDir + fileName;
        if (!new File(fileDir).exists()) {
            new File(fileDir).mkdirs();
        }
        BitmapUtils.bitmap2Path(bitmap, path);