刚才看到马斯克约战普京,蚌埠住了 目标:输入文字,生成图片,同时将图片的背景变成透明,以便用作水印。 直接代码
package com.my.fftest.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Environment;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TextToBitmap {
public static Bitmap textAsBitmap(String text, float textSize) {
TextPaint textPaint = new TextPaint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(textSize);
StaticLayout layout = new StaticLayout(text, textPaint,
(int) textPaint.measureText(text),
Layout.Alignment.ALIGN_NORMAL, 1.3f, 0.0f, true);
Bitmap bitmap = Bitmap.createBitmap(layout.getWidth() + 20,
layout.getHeight() + 20, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(10, 10);
canvas.drawColor(Color.BLUE);
layout.draw(canvas);
return getAlphaBitmap(bitmap,Color.BLUE);
}
public static String saveImageToGallery(Bitmap bitmap) {
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "myIma";
Log.i("info", "路径" + storePath);
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdirs();
}
File file = new File(appDir, System.currentTimeMillis() + ".png");
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
fos.flush();
fos.close();
if (isSuccess) {
return file.getAbsolutePath();
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static Bitmap getAlphaBitmap(Bitmap mBitmap, int mColor) {
Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmap.getWidth(),
mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
int mBitmapWidth = mAlphaBitmap.getWidth();
int mBitmapHeight = mAlphaBitmap.getHeight();
for (int i = 0; i < mBitmapHeight; i++) {
for (int j = 0; j < mBitmapWidth; j++) {
int color = mBitmap.getPixel(j, i);
if (color != mColor) {
mAlphaBitmap.setPixel(j, i, color);
}
}
}
return mAlphaBitmap;
}
}
|