實現效果圖:

手機端打水印(文字和圖片)使用的是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原生方法打水印, 應該先將壓縮分辨率, 避免OOM的情況, 但是影響清晰度; 大部分app都是將原圖傳到服務器, 在后臺打水印。
因為原生方法有分辨率和內存限制, 聽說七牛的圖片庫(支持打水印)很好用, 看看是否可以落地到各種配置的android手機中。
以上就是對Android 添加水印的方法詳解,關于Android開發的文章本站還有很多,歡迎大家搜索查閱,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答