Android编程之图片相关代码集锦

时间:2022-12-07 16:46:27

本文实例总结了Android编程之图片相关代码。分享给大家供大家参考,具体如下:

1. Bitmap转化为字符串:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param 位图
* @return 转化成的字符串
*/
public static String bitmapToString(Bitmap bitmap) {
 // 将Bitmap转换成字符串
 String string = null;
 ByteArrayOutputStream bStream = new ByteArrayOutputStream();
 bitmap.compress(CompressFormat.PNG, 100, bStream);
 byte[] bytes = bStream.toByteArray();
 string = Base64.encodeToString(bytes, Base64.DEFAULT);
 return string;
}

2.字符串转化为Bitmap:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param string 字符串
* @return 转化成的位图
*/
public static Bitmap stringToBitmap(String string) {
  // 将字符串转换成Bitmap类型
  Bitmap bitmap = null;
  try {
   byte[] bitmapArray;
   bitmapArray = Base64.decode(string, Base64.DEFAULT);
   bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return bitmap;
}

3.Bitmap转化为Drawable:

?
1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param bitmap Bitmap位图图像
* @return Drawable 转换后的Drawable对象
*/
public static Drawable bitmapToDrawable(Bitmap bitmap) {
 if (bitmap == null)
  return null;
 if (160 != bitmap.getDensity()) {
  bitmap.setDensity(160);
 }
 return new BitmapDrawable(bitmap);
}

根据图片资源ID获取Drawable对象:

?
1
2
3
4
5
6
7
8
/**
 * @param context 上下文
 * @param id  图片的资源ID
 * @return Drawable对象
 */
public static Drawable resourceToDrawable(Context context,int id) {
 return null == context ? null : bitmapToDrawable(BitmapFactory.decodeResource(context.getResources(), id));
}

byte数组转换Drawble对象:

?
1
2
3
4
5
6
7
/**
 * @param bytes byte数组
 * @return drawble对象
 */
public static Drawable byteArrayToDrawable(byte[] bytes) {
 return null == bytes ? null : bitmapToDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}

4.Drawable转化为bitmap:

?
1
2
3
4
5
6
7
8
/**
* Drawble对象转Bitmap对象
* @param drawable drawble对象
* @return bitmap对象
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
  return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap();
}

5.byte数组转换Bitmap对象:

?
1
2
3
4
5
6
7
/**
* @param bytes byte数组
* @return bitmap对象
*/
public static Bitmap byteArrayToBitmap(byte[] bytes) {
  return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}

6.图片去色,返回灰度图片(老式图片):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param bitmap 传入的bitmap
* @return 去色后的图片Bitmap对象
*/
public static Bitmap toGrayscale(Bitmap bitmap) {
  int width,height;
  height = bitmap.getHeight();
  width = bitmap.getWidth();
  Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
  Canvas c = new Canvas(bmpGrayscale);
  Paint paint = new Paint();
  ColorMatrix cm = new ColorMatrix();
  cm.setSaturation(0);
  ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
  paint.setColorFilter(f);
  c.drawBitmap(bitmap, 0, 0, paint);
  return bmpGrayscale;
}

7.对图片进行缩放:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param url   图片的路径
* @param requireSize 缩放的尺寸
* @return 缩放后的图片Bitmap对象
*/
public static Bitmap getScaleImage(String url,int requireSize) {
  BitmapFactory.Options o = new BitmapFactory.Options();
  // 此属性表示图片不加载到内存,只是读取图片的属性,包括图片的高宽
  o.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(url, o);
  int width_tmp = o.outWidth,height_tmp = o.outHeight;
  int scale = 1;
  while (true) {
   if (width_tmp / 2 < requireSize || height_tmp / 2 < requireSize)
    break;
   width_tmp /= 2;
   height_tmp /= 2;
   scale *= 2;
  }
  BitmapFactory.Options o2 = new BitmapFactory.Options();
  o2.inSampleSize = scale;
  Bitmap bmp = BitmapFactory.decodeFile(url, o2);
  return bmp;
}

8.获得图片的倒影,同时倒影渐变效果:

?
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
/**
* @param bitmap 图片源
* @return 处理后的图片Bitmap对象
*/
public static Bitmap createMirro(Bitmap bitmap) {
  int width = bitmap.getWidth();
  int height = bitmap.getHeight();
  int shadow_height = 15;
  int[] pixels = new int[width * height];
  bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
  // shadow effect
  int alpha = 0x00000000;
  for (int y = 0; y < height; y++) {
   for (int x = 0; x < width; x++) {
    int index = y * width + x;
    int r = (pixels[index] >> 16) & 0xff;
    int g = (pixels[index] >> 8) & 0xff;
    int b = pixels[index] & 0xff;
    pixels[index] = alpha | (r << 16) | (g << 8) | b;
   }
   if (y >= (height - shadow_height)) {
    alpha = alpha + 0x1F000000;
   }
  }
  // invert effect
  Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  for (int y = 0; y < height; y++) {
   bm.setPixels(pixels, y * width, width, 0, height - y - 1, width, 1);
  }
  return Bitmap.createBitmap(bm, 0, 0, width, shadow_height);
}

9.保存图片到SDCard:

?
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
/**
* @param imagePath 图片保存路径
* @param bm 被保存的bitmap对象
*/
public static void saveImgToLocal(String imagePath, Bitmap bm) {
  if (bm == null || imagePath == null || "".equals(imagePath)) {
   return;
  }
  File f = new File(imagePath);
  if (f.exists()) {
   return;
  } else {
   try {
    File parentFile = f.getParentFile();
    if (!parentFile.exists()) {
     parentFile.mkdirs();
    }
    f.createNewFile();
    FileOutputStream fos;
    fos = new FileOutputStream(f);
    bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();
   } catch (FileNotFoundException e) {
    f.delete();
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
    f.delete();
   }
  }
}

10.从SDCard中获取图片:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param imagePath 图片在SDCard中保存的路径
* @return 返回保存的bitmap对象
*/
public static Bitmap getImageFromLocal(String imagePath) {
  File file = new File(imagePath);
  if (file.exists()) {
   Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
   file.setLastModified(System.currentTimeMillis());
   return bitmap;
  }
  return null;
}

11.图片压缩处理:

?
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
/**
* 对图片进行压缩,主要是为了解决控件显示过大图片占用内存造成OOM问题。
* 一般压缩后的图片大小应该和用来展示它的控件大小相近。
* @param context 上下文
* @param resId 图片资源Id
* @param reqWidth 期望压缩的宽度
* @param reqHeight 期望压缩的高度
* @return 压缩后的图片
*/
public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) {
  final BitmapFactory.Options options = new BitmapFactory.Options();
  /*
   * 第一次解析时,inJustDecodeBounds设置为true,
   * 禁止为bitmap分配内存,虽然bitmap返回值为空,但可以获取图片大小
   */
  options.inJustDecodeBounds = true;
  BitmapFactory.decodeResource(context.getResources(), resId, options);
  final int height = options.outHeight;
  final int width = options.outWidth;
  int inSampleSize = 1;
  if (height > reqHeight || width > reqWidth) {
   final int heightRatio = Math.round((float) height / (float) reqHeight);
   final int widthRatio = Math.round((float) width / (float) reqWidth);
   inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  }
  options.inSampleSize = inSampleSize;
  //使用计算得到的inSampleSize值再次解析图片
  options.inJustDecodeBounds = false;
  return BitmapFactory.decodeResource(context.getResources(), resId, options);
}

12. 获取可用内存的最大值(App使用内存超出这个值会引起OutOfMemory异常):

?
1
2
3
4
private int getMaxMemoryForApp() {
  int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
  return maxMemory;
}

13.将图片裁剪成圆圈:

?
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
/**
* 将Bitmap处理为圆形的图片
* @param bitmap 处理之前的位图
* @return 处理之后的位图
*/
public static Bitmap circlePic(Bitmap bitmap){
  int width = bitmap.getWidth();
  int height = bitmap.getHeight();
  int r = width < height ? width/2:height/2;//圆的半径,取宽和高中较小的,以便于显示没有空白
  Bitmap outBitmap = Bitmap.createBitmap(r*2, r*2, Bitmap.Config.ARGB_8888);//创建一个刚好2r大小的Bitmap
  Canvas canvas = new Canvas(outBitmap);
  final int color =0xff424242;
  final Paint paint = new Paint();
  /**
   * 截取图像的中心的一个正方形,用于在原图中截取
   * 坐标如下:
   * 1.如果 w < h , 左上坐标(0, (h-w)/2) , 右上坐标(w, (h+w)/2) 偏移10
   * 2.如果 w > h , 左上坐标((w-h)/2, 0) , 右上坐标((w+h)/2, h) 偏移10
   */
  final Rect rect = new Rect( width < height ? 0 : (width-height)/2, width < height ? (height-width)/2 - 10 : -10,
    width < height ? width : (width+height)/2, (width < height ? (height+width)/2 - 10: height - 10));
  //创建一个直径大小的正方形,用于设置canvas的显示与设置画布截取
  final Rect rect2 = new Rect( 0, 0, r*2, r*2);
  //提高精度,用于消除锯齿
  final RectF rectF = new RectF(rect2);
  //下面是设置画笔和canvas
  paint.setAntiAlias(true);
  canvas.drawARGB(0,0,0,0);
  paint.setColor(color);
  //设置圆角,半径都为r,大小为rect2
  canvas.drawRoundRect(rectF, r, r, paint);
  //设置图像重叠时的显示方式
  paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
  //绘制图像到canvas
  canvas.drawBitmap(bitmap, rect, rect2, paint);
  return outBitmap;
 }
}

希望本文所述对大家Android程序设计有所帮助。