http://www.2cto.com/kf/201312/263638.html

Android 图片处理工具类封装
2013-12-10     0个评论   来源:Wiker Yong 的专栏  
收藏  我要投稿

android 图片处理工具类封装,包含保存图片、 写文件到SD卡,文件转Bitmap、缩放,给图片加倒影等强大功能

?
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
/**
 * 图片操作工具包
 *
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class ImageUtils {
    publicfinal static String SDCARD_MNT = "/mnt/sdcard";
    publicfinal static String SDCARD = "/sdcard";
    /** 请求相册 */
    publicstatic final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
    /** 请求相机 */
    publicstatic final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
    /** 请求裁剪 */
    publicstatic final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
    /**
     * 写图片文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
     *
     * @throws IOException
     */
    publicstatic void saveImage(Context context, String fileName, Bitmap bitmap)
            throwsIOException {
        saveImage(context, fileName, bitmap,100);
    }
    publicstatic void saveImage(Context context, String fileName,
            Bitmap bitmap,int quality) throws IOException {
        if(bitmap == null|| fileName == null|| context == null)
            return;
        FileOutputStream fos = context.openFileOutput(fileName,
                Context.MODE_PRIVATE);
        ByteArrayOutputStream stream =new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, quality, stream);
        byte[] bytes = stream.toByteArray();
        fos.write(bytes);
        fos.close();
    }
    /**
     * 写图片文件到SD卡
     *
     * @throws IOException
     */
    publicstatic void saveImageToSD(Context ctx, String filePath,
            Bitmap bitmap,int quality) throws IOException {
        if(bitmap != null) {
            File file =new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if(!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos =new BufferedOutputStream(
                    newFileOutputStream(filePath));
            bitmap.compress(CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
            if(ctx!=null){
                scanPhoto(ctx, filePath);
            }
        }
    }
    /**
     * 让Gallery上能马上看到该图片
     */
    privatestatic void scanPhoto(Context ctx, String imgFileName) {
        Intent mediaScanIntent =new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file =new File(imgFileName);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        ctx.sendBroadcast(mediaScanIntent);
    }
    /**
     * 获取bitmap
     *
     * @param context
     * @param fileName
     * @return
     */
    publicstatic Bitmap getBitmap(Context context, String fileName) {
        FileInputStream fis =null;
        Bitmap bitmap =null;
        try{
            fis = context.openFileInput(fileName);
            bitmap = BitmapFactory.decodeStream(fis);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }finally {
            try{
                fis.close();
            }catch (Exception e) {
            }
        }
        returnbitmap;
    }
    /**
     * 获取bitmap
     *
     * @param filePath
     * @return
     */
    publicstatic Bitmap getBitmapByPath(String filePath) {
        returngetBitmapByPath(filePath, null);
    }
    publicstatic Bitmap getBitmapByPath(String filePath,
            BitmapFactory.Options opts) {
        FileInputStream fis =null;
        Bitmap bitmap =null;
        try{
            File file =new File(filePath);
            fis =new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis,null, opts);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }finally {
            try{
                fis.close();
            }catch (Exception e) {
            }
        }
        returnbitmap;
    }
    /**
     * 获取bitmap
     *
     * @param file
     * @return
     */
    publicstatic Bitmap getBitmapByFile(File file) {
        FileInputStream fis =null;
        Bitmap bitmap =null;
        try{
            fis =new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }finally {
            try{
                fis.close();
            }catch (Exception e) {
            }
        }
        returnbitmap;
    }
    /**
     * 使用当前时间戳拼接一个唯一的文件名
     *
     * @param format
     * @return
     */
    publicstatic String getTempFileName() {
        SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
        String fileName = format.format(newTimestamp(System
                .currentTimeMillis()));
        returnfileName;
    }
    /**
     * 获取照相机使用的目录
     *
     * @return
     */
    publicstatic String getCamerPath() {
        returnEnvironment.getExternalStorageDirectory() + File.separator
                +"FounderNews" + File.separator;
    }
    /**
     * 判断当前Url是否标准的content://样式,如果不是,则返回绝对路径
     *
     * @param uri
     * @return
     */
    publicstatic String getAbsolutePathFromNoStandardUri(Uri mUri) {
        String filePath =null;
        String mUriString = mUri.toString();
        mUriString = Uri.decode(mUriString);
        String pre1 ="file://" + SDCARD + File.separator;
        String pre2 ="file://" + SDCARD_MNT + File.separator;
        if(mUriString.startsWith(pre1)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre1.length());
        }else if(mUriString.startsWith(pre2)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre2.length());
        }
        returnfilePath;
    }
    /**
     * 通过uri获取文件的绝对路径
     *
     * @param uri
     * @return
     */
    publicstatic String getAbsoluteImagePath(Activity context, Uri uri) {
        String imagePath ="";
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.managedQuery(uri, proj,// Which columns to
                                                        // return
                null,// WHERE clause; which rows to return (all rows)
                null,// WHERE clause selection arguments (none)
                null);// Order-by clause (ascending by name)
        if(cursor != null) {
            intcolumn_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if(cursor.getCount() > 0&& cursor.moveToFirst()) {
                imagePath = cursor.getString(column_index);
            }
        }
        returnimagePath;
    }
    /**
     * 获取图片缩略图 只有Android2.1以上版本支持
     *
     * @param imgName
     * @param kind
     *            MediaStore.Images.Thumbnails.MICRO_KIND
     * @return
     */
    publicstatic Bitmap loadImgThumbnail(Activity context, String imgName,
            intkind) {
        Bitmap bitmap =null;
        String[] proj = { MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DISPLAY_NAME };
        Cursor cursor = context.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
                MediaStore.Images.Media.DISPLAY_NAME +"='" + imgName +"'",
                null,null);
        if(cursor != null&& cursor.getCount() > 0&& cursor.moveToFirst()) {
            ContentResolver crThumb = context.getContentResolver();
            BitmapFactory.Options options =new BitmapFactory.Options();
            options.inSampleSize =1;
            bitmap = MethodsCompat.getThumbnail(crThumb, cursor.getInt(0),
                    kind, options);
        }
        returnbitmap;
    }
    publicstatic Bitmap loadImgThumbnail(String filePath,int w, inth) {
        Bitmap bitmap = getBitmapByPath(filePath);
        returnzoomBitmap(bitmap, w, h);
    }
    /**
     * 获取SD卡中最新图片路径
     *
     * @return
     */
    publicstatic String getLatestImage(Activity context) {
        String latestImage =null;
        String[] items = { MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA };
        Cursor cursor = context.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items,null,
                null, MediaStore.Images.Media._ID +" desc");
        if(cursor != null&& cursor.getCount() > 0) {
            cursor.moveToFirst();
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor
                    .moveToNext()) {
                latestImage = cursor.getString(1);
                break;
            }
        }
        returnlatestImage;
    }
    /**
     * 计算缩放图片的宽高
     *
     * @param img_size
     * @param square_size
     * @return
     */
    publicstatic int[] scaleImageSize(int[] img_size,int square_size) {
        if(img_size[0] <= square_size && img_size[1] <= square_size)
            returnimg_size;
        doubleratio = square_size
                / (double) Math.max(img_size[0], img_size[1]);
        returnnew int[] { (int) (img_size[0] * ratio),
                (int) (img_size[1] * ratio) };
    }
    /**
     * 创建缩略图
     *
     * @param context
     * @param largeImagePath
     *            原始大图路径
     * @param thumbfilePath
     *            输出缩略图路径
     * @param square_size
     *            输出图片宽度
     * @param quality
     *            输出图片质量
     * @throws IOException
     */
    publicstatic void createImageThumbnail(Context context,
            String largeImagePath, String thumbfilePath,int square_size,
            intquality) throwsIOException {
        BitmapFactory.Options opts =new BitmapFactory.Options();
        opts.inSampleSize =1;
        // 原始图片bitmap
        Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
        if(cur_bitmap == null)
            return;
        // 原始图片的高宽
        int[] cur_img_size =new int[] { cur_bitmap.getWidth(),
                cur_bitmap.getHeight() };
        // 计算原始图片缩放后的宽高
        int[] new_img_size = scaleImageSize(cur_img_size, square_size);
        // 生成缩放后的bitmap
        Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
                new_img_size[1]);
        // 生成缩放后的图片文件
        saveImageToSD(null,thumbfilePath, thb_bitmap, quality);
    }
    /**
     * 放大缩小图片
     *
     * @param bitmap
     * @param w
     * @param h
     * @return
     */
    publicstatic Bitmap zoomBitmap(Bitmap bitmap,int w, inth) {
        Bitmap newbmp =null;
        if(bitmap != null) {
            intwidth = bitmap.getWidth();
            intheight = bitmap.getHeight();
            Matrix matrix =new Matrix();
            floatscaleWidht = ((float) w / width);
            floatscaleHeight = ((float) h / height);
            matrix.postScale(scaleWidht, scaleHeight);
            newbmp = Bitmap.createBitmap(bitmap,0, 0, width, height, matrix,
                    true);
        }
        returnnewbmp;
    }
    publicstatic Bitmap scaleBitmap(Bitmap bitmap) {
        // 获取这个图片的宽和高
        intwidth = bitmap.getWidth();
        intheight = bitmap.getHeight();
        // 定义预转换成的图片的宽度和高度
        intnewWidth = 200;
        intnewHeight = 200;
        // 计算缩放率,新尺寸除原始尺寸
        floatscaleWidth = ((float) newWidth) / width;
        floatscaleHeight = ((float) newHeight) / height;
        // 创建操作图片用的matrix对象
        Matrix matrix =new Matrix();
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        // 旋转图片 动作
        // matrix.postRotate(45);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap,0, 0, width, height,
                matrix,true);
        returnresizedBitmap;
    }
    /**
     * (缩放)重绘图片
     *
     * @param context
     *            Activity
     * @param bitmap
     * @return
     */
    publicstatic Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
        DisplayMetrics dm =new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        intrHeight = dm.heightPixels;
        intrWidth = dm.widthPixels;
        // float rHeight=dm.heightPixels/dm.density+0.5f;
        // float rWidth=dm.widthPixels/dm.density+0.5f;
        // int height=bitmap.getScaledHeight(dm);
        // int width = bitmap.getScaledWidth(dm);
        intheight = bitmap.getHeight();
        intwidth = bitmap.getWidth();
        floatzoomScale;
        /** 方式1 **/
        // if(rWidth/rHeight>width/height){//以高为准
        // zoomScale=((float) rHeight) / height;
        // }else{
        // //if(rWidth/rHeight<width height)="" 以宽为准="" zoomscale="((float)" rwidth)="" width;="" }="" **="" 方式2="" if(width*1.5="">= height) {//以宽为准
        // if(width >= rWidth)
        // zoomScale = ((float) rWidth) / width;
        // else
        // zoomScale = 1.0f;
        // }else {//以高为准
        // if(height >= rHeight)
        // zoomScale = ((float) rHeight) / height;
        // else
        // zoomScale = 1.0f;
        // }
        /** 方式3 **/
        if(width >= rWidth)
            zoomScale = ((float) rWidth) / width;
        else
            zoomScale =1.0f;
        // 创建操作图片用的matrix对象
        Matrix matrix =new Matrix();
        // 缩放图片动作
        matrix.postScale(zoomScale, zoomScale);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap,0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix,true);
        returnresizedBitmap;
    }
    /**
     * 将Drawable转化为Bitmap
     *
     * @param drawable
     * @return
     */
    publicstatic Bitmap drawableToBitmap(Drawable drawable) {
        intwidth = drawable.getIntrinsicWidth();
        intheight = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
                .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565);
        Canvas canvas =new Canvas(bitmap);
        drawable.setBounds(0,0, width, height);
        drawable.draw(canvas);
        returnbitmap;
    }
    /**
     * 获得圆角图片的方法
     *
     * @param bitmap
     * @param roundPx
     *            一般设成14
     * @return
     */
    publicstatic Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas =new Canvas(output);
        finalint color = 0xff424242;
        finalPaint paint = newPaint();
        finalRect rect = newRect(0,0, bitmap.getWidth(), bitmap.getHeight());
        finalRectF rectF = newRectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0,0, 0,0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(newPorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        returnoutput;
    }
    /**
     * 获得带倒影的图片方法
     *
     * @param bitmap
     * @return
     */
    publicstatic Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
        finalint reflectionGap = 4;
        intwidth = bitmap.getWidth();
        intheight = bitmap.getHeight();
        Matrix matrix =new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap,0, height / 2,
                width, height /2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                (height + height /2), Config.ARGB_8888);
        Canvas canvas =new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap,0, 0,null);
        Paint deafalutPaint =new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
        canvas.drawBitmap(reflectionImage,0, height + reflectionGap,null);
        Paint paint =new Paint();
        LinearGradient shader =new LinearGradient(0, bitmap.getHeight(),0,
                bitmapWithReflection.getHeight() + reflectionGap,0x70ffffff,
                0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(newPorterDuffXfermode(Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                + reflectionGap, paint);
        returnbitmapWithReflection;
    }
    /**
     * 将bitmap转化为drawable
     *
     * @param bitmap
     * @return
     */
    publicstatic Drawable bitmapToDrawable(Bitmap bitmap) {
        Drawable drawable =new BitmapDrawable(bitmap);
        returndrawable;
    }
    /**
     * 获取图片类型
     *
     * @param file
     * @return
     */
    publicstatic String getImageType(File file) {
        if(file == null || !file.exists()) {
            returnnull;
        }
        InputStream in =null;
        try{
            in =new FileInputStream(file);
            String type = getImageType(in);
            returntype;
        }catch (IOException e) {
            returnnull;
        }finally {
            try{
                if(in != null) {
                    in.close();
                }
            }catch (IOException e) {
            }
        }
    }
    /**
     * 获取图片的类型信息
     *
     * @param in
     * @return
     * @see #getImageType(byte[])
     */
    publicstatic String getImageType(InputStream in) {
        if(in == null) {
            returnnull;
        }
        try{
            byte[] bytes =new byte[8];
            in.read(bytes);
            returngetImageType(bytes);
        }catch (IOException e) {
            returnnull;
        }
    }
    /**
     * 获取图片的类型信息
     *
     * @param bytes
     *            2~8 byte at beginning of the image file
     * @return image mimetype or null if the file is not image
     */
    publicstatic String getImageType(byte[] bytes) {
        if(isJPEG(bytes)) {
            return"image/jpeg";
        }
        if(isGIF(bytes)) {
            return"image/gif";
        }
        if(isPNG(bytes)) {
            return"image/png";
        }
        if(isBMP(bytes)) {
            return"application/x-bmp";
        }
        returnnull;
    }
    privatestatic booleanisJPEG(byte[] b) {
        if(b.length < 2) {
            returnfalse;
        }
        return(b[0] == (byte)0xFF) && (b[1] == (byte)0xD8);
    }
    privatestatic booleanisGIF(byte[] b) {
        if(b.length < 6) {
            returnfalse;
        }
        returnb[0] =='G' && b[1] =='I' && b[2] =='F' && b[3] =='8'
                && (b[4] =='7' || b[4] =='9') && b[5] =='a';
    }
    privatestatic booleanisPNG(byte[] b) {
        if(b.length < 8) {
            returnfalse;
        }
        return(b[0] == (byte)137 && b[1] == (byte)80 && b[2] == (byte)78
                && b[3] == (byte)71 && b[4] == (byte)13 && b[5] == (byte)10
                && b[6] == (byte)26 && b[7] == (byte)10);
    }
    privatestatic booleanisBMP(byte[] b) {
        if(b.length < 2) {
            returnfalse;
        }
        return(b[0] ==0x42) && (b[1] ==0x4d);
    }

  1. /**
  2. * 添加文字到图片,类似水印文字。
  3. * @param gContext
  4. * @param gResId
  5. * @param gText
  6. * @return
  7. */
  8. public static Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {
  9. Resources resources = gContext.getResources();
  10. float scale = resources.getDisplayMetrics().density;
  11. Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
  12. android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
  13. // set default bitmap config if none
  14. if (bitmapConfig == null) {
  15. bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
  16. }
  17. // resource bitmaps are imutable,
  18. // so we need to convert it to mutable one
  19. bitmap = bitmap.copy(bitmapConfig, true);
  20. Canvas canvas = new Canvas(bitmap);
  21. // new antialised Paint
  22. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  23. // text color - #3D3D3D
  24. paint.setColor(Color.rgb(61,61,61));
  25. // text size in pixels
  26. paint.setTextSize((int) (14 * scale*5));
  27. // text shadow
  28. paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
  29. // draw text to the Canvas center
  30. Rect bounds = new Rect();
  31. paint.getTextBounds(gText, 0, gText.length(), bounds);
  32. //      int x = (bitmap.getWidth() - bounds.width()) / 2;
  33. //      int y = (bitmap.getHeight() + bounds.height()) / 2;
  34. //draw  text  to the bottom
  35. int x = (bitmap.getWidth() - bounds.width())/10*9 ;
  36. int y = (bitmap.getHeight() + bounds.height())/10*9;
  37. canvas.drawText(gText, x , y, paint);
  38. return bitmap;
  39. }
}

Android 图片处理工具类封装2相关推荐

  1. Android 图片处理工具类汇总

    很有用的Android图片处理工具,实现各种图片处理效果 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 ...

  2. android 图片缓存工具类,Android工具类系列-Glide图片缓存与圆角

    Glide的图片缓存和清除图片缓存 public class GlideCacheUtil { private static GlideCacheUtil inst; public static Gl ...

  3. android图片下载工具类

    public class HttpRequestImage {public static String headpath="/sdcard/head/";//图片保存地址 // p ...

  4. Android 图片下载工具类

    public class DownGoodsImage {private Context context;private String filePath;private String fileName ...

  5. ImageView可直接调用的,根据URL设置图片的工具类

    ImageView 是Android编程中最常用的组件之一. 但是根据图片的URL设置图片却很麻烦.因为获取网络图片的操作必须在异步线程中进行,根据URL设置ImageView图片就可能需要进行线程间 ...

  6. Android常用的工具类

    2019独角兽企业重金招聘Python工程师标准>>> 最新最准确内容建议直接访问原文:Android常用的工具类 主要介绍总结的Android开发中常用的工具类,大部分同样适用于J ...

  7. Android开发常用工具类集合

    转载自:https://blog.csdn.net/xiaoyi_tdcq/article/details/52902844 Android开发常用工具类集合 android开发中为了避免重复造轮子, ...

  8. android 快速开发工具类,android面试知识点

    项目地址:570622566/FastAndrUtils  简介:android 快速开发工具类 更多:作者   提 Bug   官网 标签: Fastandrutils 是一套整理修改整合的 and ...

  9. Redis工具类封装讲解和实战

    Redis工具类封装讲解和实战     简介:高效开发方式 Redis工具类封装讲解和实战         1.常用客户端 https://redisdesktop.com/download      ...

最新文章

  1. 13、Excutors 结合 ThreadFactory 自动给线程加上线程名
  2. android 微信跨境支付,微信跨境支付.pdf
  3. [转载] 七龙珠第一部——第110话 加油 孙悟空
  4. 苹果X可以升级5G吗_苹果x可以用5g网络吗
  5. android和linux操作系统的区别
  6. keep健身软件电脑版_电脑软件:优酷 (优化版)
  7. leetcode 21 合并两个有序链表 (python)
  8. 测试方法-等价类划分法
  9. 很值得看看的中文翻译The Django Book
  10. Python基础语法知识1
  11. 光谱数据计算CIE值(三刺激值、CIE1931、CIE1976、CCT)软件
  12. 微信小程序tabbar图片路径问题
  13. Adobe Audition 2020 for Mac安装不了怎么办?Au下载安装教程来啦 内附系统要求
  14. Android Q Data Setup for Short Connection
  15. Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes解决方法
  16. mysql-python:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h' 非权威指南
  17. “宅米”VS“校呵呵”竞品分析报告
  18. OrangePi PC 玩Linux主线内核踩坑之旅(二)之制作镜像后的查遗补缺
  19. html打印预览 分页,有分页功能的WEB打印_js
  20. LTE下行物理层传输机制(4)-CCE

热门文章

  1. Doxygen简介及使用说明
  2. 2019 CCPC-Wannafly Winter Camp Day8 (Div2, onsite) 补题记录
  3. Windows 7 新功能 - BitLocker To Go
  4. 喜欢NBA的朋友快来这里看第一阶段的全明星投票结果!!!(更新到第二阶段、第三阶段)
  5. 转行程序员日记---2020-10-12【不是孤独一人】
  6. bread是可数还是不可数_学了20年英语才明白:bread为什么是不可数名词?
  7. 开源 区块链_区块链将如何影响开源
  8. Udacity Deep Learning课程作业(五)
  9. Android 多语言支持
  10. java中protected权限与默认权限的区别