这篇文章主要介绍了Android中如何给图片添加水印的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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中如何给图片添加水印”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Android中如何给图片添加水印”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。