1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
public static File Watermark(File file){ Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); canvas.drawBitmap(bitmap, 0, 0, null);
Bitmap watermarkImg = getWatermarkImg(newBitmap.getWidth() > newBitmap.getHeight() ? newBitmap.getHeight() : newBitmap.getWidth()); Paint paint = new Paint(); canvas.drawBitmap(watermarkImg, margin , (newBitmap.getHeight() - watermarkImg.getHeight() - margin), paint);
paint.setColor(Color.rgb(0xff, 0xff, 0xff)); paint.setTextSize(watermarkImg.getHeight() / 4); canvas.drawText("要添加的水印文字", margin * 2 + watermarkImg.getWidth(), newBitmap.getHeight() - (watermarkImg.getHeight() / 2) - margin, paint);
canvas.save(Canvas.ALL_SAVE_FLAG); try { file.delete(); FileOutputStream fos = new FileOutputStream(file); newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (Exception e) {
} return file; }
private static Bitmap getWatermarkImg(int width) {
Bitmap imgWatermark = null; try { imgWatermark = BitmapFactory.decodeStream( MyApp.getInstance().getAssets().open("shuiyin.png"));
Matrix matrix = new Matrix(); float scale = width * 1.0f / 7 / imgWatermark.getWidth(); matrix.postScale(scale, scale , imgWatermark.getWidth() * 1.0f / 2, imgWatermark.getHeight() * 1.0f / 2); imgWatermark = Bitmap.createBitmap(imgWatermark, 0, 0, imgWatermark.getWidth(), imgWatermark.getHeight() , matrix, true); } catch (IOException e) { imgWatermark = null; e.printStackTrace(); }
return imgWatermark; }
|