本篇文章为大家展示了Android中怎么给图片添加水印,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Android 图片添加水印的实现方法
手机端打水印(文字和图片)使用的是Bitmap、Matrix和Canvas类的一些方法, 可以实现拉伸、旋转、位移等等效果。 原理很简单, 就是在画布Canvas上绘制图形、图片、文字等等, 得到你想要的效果图片。
/*
添加全屏斜着45度的文字
/
public static Bitmap drawCenterLable(Context context, Bitmap bmp, String text) {
float scale = context.getResources().getDisplayMetrics().density;
//创建一样大小的图片
Bitmap newBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.ARGB_8888);
//创建画布
Canvas canvas = new Canvas(newBmp);
canvas.drawBitmap(bmp, 0, 0, null); //绘制原始图片
canvas.save();
canvas.rotate(45); //顺时针转45度
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.argb(50, 255, 255, 255)); //白色半透明
paint.setTextSize(100 scale);
paint.setDither(true);
paint.setFilterBitmap(true);
Rect rectText = new Rect(); //得到text占用宽高, 单位:像素
paint.getTextBounds(text, 0, text.length(), rectText);
double beginX = (bmp.getHeight()/2 - rectText.width()/2) * 1.4; //45度角度值是1.414
double beginY = (bmp.getWidth()/2 - rectText.width()/2) * 1.4;
canvas.drawText(text, (int)beginX, (int)beginY, paint);
canvas.restore();
return newBmp;
}
使用44KB的png图片验证效率:
long begin = System.currentTimeMillis();
Bitmap destBmp = ImageUtil.drawCenterLable(this, sourBitmap, "某某公司专用");
long end = System.currentTimeMillis();
Log.d("brycegao", "打水印用时:" + (end-begin) + "毫秒");
mWartermarkImage.setImageBitmap(destBmp);
小米4手机输出: D/brycegao: 打水印用时:69毫秒
使用3M字节的jpg图片测试打水印,报OOM错误。
java.lang.OutOfMemoryError: Failed to allocate a 467251212 byte allocation with 16767536 free bytes and 110MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:613)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:446)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:469)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:501)
上述内容就是Android中怎么给图片添加水印,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。