Bitmap和Drawable的相互转换,图片缩放,倒圆角,倒影等的实现

来源:互联网 发布:is淘宝刷平台哪个好 编辑:程序博客网 时间:2024/05/27 20:55

注 :希望刚开启开发之路的 各位少年 能够多写一些自己经常使用的工具类, 提高自己的能力和开发效率

话不多说  直接源码给上.

   /**
 * 图片工具类
 */
public final class ImageTools {

 
  /**
     * 从资源中获取Bitmap
     * @param id
     *    drawable资源的ID
     * @return 返回Bitmap图片
     */
    public static Bitmap fromResGetBmp(Context context, int id) {
     
     Resources res = context.getResources();
     Bitmap bmp = BitmapFactory.decodeResource(res, id);
     return bmp;
    }
   
    /**
     * 从资源中获取Drawable
     * @param context
     * @param id
     * @return
     */
    public static Drawable fromResGetDrawable(Context context, int id) {
     
     Drawable drawable = context.getResources().getDrawable(id);
     return drawable;
    }
   
 /**
  *  drawable转化为bitmap
  *
  * @param drawable
  * @return
  */
 public static Bitmap drawableToBitmap(Drawable drawable) {
  int w = drawable.getIntrinsicWidth();
  int h = drawable.getIntrinsicHeight();
  
  //关于 图片转化 质量的设置 , ARGB_8888>RGB_565,还有其他几种模式可以上网查找,这里就不做一一说明了
  Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
    : Bitmap.Config.RGB_565;
  Bitmap bitmap = Bitmap.createBitmap(w, h, config);
  Canvas canvas = new Canvas(bitmap);
  drawable.setBounds(0, 0, w, h);
  drawable.draw(canvas);
  return bitmap;
 }

 /**
  * Bitmap转化为drawable
  *
  * @param bitmap
  * @return
  */
 public static Drawable bitmapToDrawable(Context context, Bitmap bitmap) {
  return new BitmapDrawable(context.getResources(), bitmap);
 }
 
 /**
  * Input stream转化为bitmap
  *
  * @param inputStream
  * @return
  * @throws Exception
  */
 public static Bitmap inputStreamToBitmap(InputStream inputStream)
   throws Exception {
  return BitmapFactory.decodeStream(inputStream);
 }

 /**
  * Byte transfer转化为bitmap
  *
  * @param byteArray
  * @return
  */
 public static Bitmap byteToBitmap(byte[] byteArray) {
  if (byteArray.length != 0) {
   return BitmapFactory
     .decodeByteArray(byteArray, 0, byteArray.length);
  } else {
   return null;
  }
 }

 /**
  * Byte transfer转化为drawable
  *
  * @param byteArray
  * @return
  */
 public static Drawable byteToDrawable(byte[] byteArray) {
  ByteArrayInputStream ins = null;
  if (byteArray != null) {
   ins = new ByteArrayInputStream(byteArray);
  }
  return Drawable.createFromStream(ins, null);
 }

 /**
  * Bitmap transfer转化为bytes
  *
  * @param byteArray
  * @return
  */
 public static byte[] bitmapToBytes(Bitmap bm) {
  
  byte[] bytes = null;
  if (bm != null) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
   bytes = baos.toByteArray();
  }
  return bytes;
 }

 /**
  * Drawable transfer转化为bytes
  *
  * @param drawable
  * @return
  */
 public static byte[] drawableToBytes(Drawable drawable) {
  BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
  Bitmap bitmap = bitmapDrawable.getBitmap();
  byte[] bytes = bitmapToBytes(bitmap);
  ;
  return bytes;
 }

 /**
  * Base64转化为byte[]
  */
 public static byte[] base64ToBytes(String base64) throws IOException {
  byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
  return bytes;
 }

 /**
  * Byte[]转化为base64
  */
 public static String bytesTobase64(byte[] bytes) {
  String base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
  return base64;
 }

 /**
  * Create 倒影  images
  *
  * @param bitmap
  * @return
  */
 public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
  final int reflectionGap = 4;
  int w = bitmap.getWidth();
  int h = bitmap.getHeight();

  Matrix matrix = new Matrix();
  matrix.preScale(1, -1);

  Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w,
    h / 2, matrix, false);

  Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2),
    Config.ARGB_8888);

  Canvas canvas = new Canvas(bitmapWithReflection);
  canvas.drawBitmap(bitmap, 0, 0, null);
  Paint deafalutPaint = new Paint();
  canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);

  canvas.drawBitmap(reflectionImage, 0, h + 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(new PorterDuffXfermode(Mode.DST_IN));
  // Draw a rectangle using the paint with our linear gradient
  canvas.drawRect(0, h, w, bitmapWithReflection.getHeight()
    + reflectionGap, paint);

  return bitmapWithReflection;
 }

 /**
  * 获取圆角的图片
  *
  * @param bitmap
  * @param roundPx
  *            5 10
  * @return
  */
 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
  int w = bitmap.getWidth();
  int h = bitmap.getHeight();
  Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
  Canvas canvas = new Canvas(output);
  final int color = 0xff424242;
  final Paint paint = new Paint();
  final Rect rect = new Rect(0, 0, w, h);
  final RectF rectF = new RectF(rect);
  paint.setAntiAlias(true);
  canvas.drawARGB(0, 0, 0, 0);
  paint.setColor(color);
  canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
  paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
  canvas.drawBitmap(bitmap, rect, rect, paint);

  return output;
 }

 /**
  * 调整图片(类型:bitmap)大小
  *
  * @param bitmap
  * @param width
  * @param height
  * @return
  */
 public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {

  int w = bitmap.getWidth();
  int h = bitmap.getHeight();
  Matrix matrix = new Matrix();
  float scaleWidth = ((float) width / w);
  float scaleHeight = ((float) height / h);
  matrix.postScale(scaleWidth, scaleHeight);
  Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
  return newbmp;
 }

 /**
  * 调整图片(类型:drawable)大小
  * @param drawable
  * @param w
  * @param h
  * @return
  */
 public static Drawable zoomDrawable(Context context, Drawable drawable, int w, int h) {
  int width = drawable.getIntrinsicWidth();
  int height = drawable.getIntrinsicHeight();
  Bitmap oldbmp = drawableToBitmap(drawable);
  Matrix matrix = new Matrix();
  float sx = ((float) w / width);
  float sy = ((float) h / height);
  matrix.postScale(sx, sy);
  Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
    matrix, true);
  return new BitmapDrawable(context.getResources(), newbmp);
 }
 
 /**
  * 从SDcard中获取图片
  * @param photoName
  * @return
  */
 public static Bitmap getPhotoFromSDCard(String path,String photoName){
  Bitmap photoBitmap = BitmapFactory.decodeFile(path + "/" +photoName +".jpg");
  if (photoBitmap == null) {
   return null;
  }else {
   return photoBitmap;
  }
 }
 
 /**
  * 根据路径获取图片,如没有则返回默认图片
  * @param path
  * @param defaultBitmap
  * @return
  */
 public static Bitmap getBitmapForPath(String path, Bitmap defaultBitmap){
  Bitmap decodeFile = BitmapFactory.decodeFile(path);
  if(decodeFile == null){
   return defaultBitmap;
  }
  return decodeFile;
 }
 
 
 /**
  * 检测SDcard是否存在
  * @return
  */
 public static boolean checkSDCardAvailable(){
  return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
 }
 
 /**
  * 判断SDcard中是否存在此图片
  * @param fileName
  * @return
  */
 public static boolean findPhotoFromSDCard(String path, String photoName){
  boolean flag = false;
  
  if (checkSDCardAvailable()) {
   File dir = new File(path);
   if (dir.exists()) {
    File folders = new File(path);
    File photoFile[] = folders.listFiles();
    for (int i = 0; i < photoFile.length; i++) {
     String fileName = photoFile[i].getName().split("\\.")[0];
     if (fileName.equals(photoName)) {
      flag = true;
     }
    }
   }else {
    flag = false;
   }
//   File file = new File(path + "/" + photoName  + ".jpg" );
//   if (file.exists()) {
//    flag = true;
//   }else {
//    flag = false;
//   }
   
  }else {
   flag = false;
  }
  return flag;
 }
 
 /**
  * 保存图片在SDcard中
  * @param photoBitmap
  * @param photoName
  * @param path
  */
 public static void savePhotoToSDCard(Bitmap photoBitmap,String path,String photoName){
  if (checkSDCardAvailable()) {
   File dir = new File(path);
   if (!dir.exists()){
    dir.mkdirs();
   }
   
   File photoFile = new File(path , photoName);
   FileOutputStream fileOutputStream = null;
   try {
    fileOutputStream = new FileOutputStream(photoFile);
    if (photoBitmap != null) {
     if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
      fileOutputStream.flush();
//      fileOutputStream.close();
     }
    }
   } catch (FileNotFoundException e) {
    photoFile.delete();
    e.printStackTrace();
   } catch (IOException e) {
    photoFile.delete();
    e.printStackTrace();
   } finally{
    try {
     fileOutputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 
 /**
  * 从SDcard中删除图片(可以删除整个目录的,或者单张的)
  * @param context
  * @param path
  * file:///sdcard/temp.jpg
  */
 public static void deleteAllPhoto(String path){
  if (checkSDCardAvailable()) {
   File folder = new File(path);
   File[] files = folder.listFiles();
   for (int i = 0; i < files.length; i++) {
    files[i].delete();
   }
  }
 }
 
 /**
  * 从SDcard中删除规定的图片
  * @param path
  * @param fileName
  */
 public static void deletePhotoAtPathAndName(String path, String fileName){
  if (checkSDCardAvailable()) {
   File folder = new File(path);
   File[] files = folder.listFiles();
   for (int i = 0; i < files.length; i++) {
    if (files[i].getName().split("\\.")[0].equals(fileName)) {
     files[i].delete();
    }
   }
  }
 }
 
 /**
  * 获取drawable需要的图片
  * @param context
  * @param arrayImage
  * @return
  */
 public static ArrayList<Integer> getImagesByArray(Context context, int arrayImage) {
  
  ArrayList<Integer> images = new ArrayList<Integer>();
     String packageName = context.getResources().getResourcePackageName(arrayImage);
        String[] extras = context.getResources().getStringArray(arrayImage);
        for (String extra : extras) {
            int res = context.getResources().getIdentifier(extra, "drawable", packageName);
            if (res != 0) {
             images.add(res);
            }
        }
        return images;
    }



0 0
原创粉丝点击