图片相关处理类BitmapUtil

public class BitmapUtils {
    /**
     * 获取网络图片资源
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url){
        URL myFileURL;
        Bitmap bitmap=null;
        try{
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
            //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无,没有影响
            //conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }
/**
 * 以最省内存的方式读取本地资源的图片
 * @param context
 * @param resId
 * @return
 */  
 public static Bitmap readBitMap(Context context,int resId){  

     BitmapFactory.Options opt = new BitmapFactory.Options();  
     opt.inPreferredConfig = Bitmap.Config.RGB_565;   
     opt.inPurgeable = true;  
     opt.inInputShareable = true;  
     //获取资源图片  
     InputStream is = context.getResources().openRawResource(resId); 
     return BitmapFactory.decodeStream(is,null,opt);  
  }



/**
 * 通过传入Path和ImageView加载相应的图片
 * 对图片加载的优化
 * @param imageView
 */
public static void loadPicture(ImageView imageView,String Path){
    int reqWidth = imageView.getWidth();
    int reqHeight = imageView.getHeight();
    Bitmap bitmap = decodeSampledBitmapFromFile(Path,reqWidth,reqHeight);

    if (bitmap != null){
        imageView.setImageBitmap(bitmap);
    }
}
public static Bitmap decodeSampledBitmapFromFile(String strPath,int reqWidth,int reqHeight) {   
    // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小   
    final BitmapFactory.Options options = new BitmapFactory.Options();   
    options.inJustDecodeBounds = true;   
    BitmapFactory.decodeFile(strPath,options);
    // 调用上面定义的方法计算inSampleSize值   
    options.inSampleSize = calculateInSampleSize(options,reqHeight);   
    // 使用获取到的inSampleSize值再次解析图片   
    options.inJustDecodeBounds = false;   
    return BitmapFactory.decodeFile(strPath,options);   
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqHeight) {   
    // 源图片的高度和宽度   
    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的值,这样可以保证最终图片的宽和高   
        // 一定都会大于等于目标的宽和高。   
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;   
    }   
    return inSampleSize;   
}



 /**
 *保存图片到文件
 */
public static File saveBitmapToFile(Bitmap bitmap) {
    //如果相等的话表示当前的sdcard挂载在手机上并且是可用的  
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
        String storePath = Environment.getExternalStorageDirectory().toString() + "/yingzhidao/"+"header.jpg";
        File file = new File(storePath);
        if (!file.exists()){
            file.mkdir();
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    return null;
}



/**
 * 压缩图片到制定大小
 * @param bitmap
 * @param size
 * @return
 */
public static Bitmap imageZoom(Bitmap bitmap,double size) {
    Bitmap targetBitmap = null;
    targetBitmap = bitmap;
    //图片允许最大空间   单位:KB
    double maxSize =size;
    //将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    targetBitmap.compress(Bitmap.CompressFormat.JPEG,baos);
    byte[] b = baos.toByteArray();
    //将字节换成KB
    double mid = b.length/1024;
    //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
    if (mid > maxSize) {
        //获取bitmap大小 是允许最大大小的多少倍
        double i = mid / maxSize;
        //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
        targetBitmap = zoomImage(targetBitmap,targetBitmap.getWidth() / Math.sqrt(i),targetBitmap.getHeight() / Math.sqrt(i));
    }
    return targetBitmap;
}
public static Bitmap zoomImage(Bitmap bgimage,double newWidth,double newHeight) {
    // 获取这个图片的宽和高
    float width = bgimage.getWidth();
    float height = bgimage.getHeight();
    // 创建操作图片用的matrix对象
    Matrix matrix = new Matrix();
    // 计算宽高缩放率
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // 缩放图片动作
    matrix.postScale(scaleWidth,scaleHeight);
    Bitmap bitmap = Bitmap.createBitmap(bgimage,(int) width,(int) height,matrix,true);
    return bitmap;
}



/**
 *为图片添加水印
 */
public static Bitmap drawTextToBitmap(Context gContext,int gResId,String text) {
    Resources resources = gContext.getResources();
    // float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap =
            BitmapFactory.decodeResource(resources,gResId);

    android.graphics.Bitmap.Config bitmapConfig =
            bitmap.getConfig();
    // set default bitmap config if none
    if(bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are imutable,// so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig,true);

    int height = bitmap.getHeight();
    int width = bitmap.getWidth();

    // new antialised Paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(255,255,255));
    // text size in pixels
    paint.setTextSize(32);
    // text shadow
    // paint.setShadowLayer(1f,0f,1f,Color.WHITE);

    // draw text to the Canvas center
    Rect bounds = new Rect();
    paint.getTextBounds(text,text.length(),bounds);
    Log.i("NEC","text width:"+bounds.width());
    Log.i("NEC","text high:" + bounds.height());

    int targetWidth = bounds.width()+40;

    Matrix matrix = new Matrix();
    float scaleWidth = ((float) targetWidth) / width;
    float scaleHeight = ((float) height) / height;
    matrix.postScale(scaleWidth,scaleHeight);

    Bitmap scaleBitmap = Bitmap.createBitmap(bitmap,width,height,true);

    int x = (scaleBitmap.getWidth() - bounds.width())/2;
    int y = (scaleBitmap.getHeight() + bounds.height())/2-8;

    Canvas canvas = new Canvas(scaleBitmap);
    canvas.drawText(text,x,y,paint);

    if(!bitmap.isRecycled())
    {
        bitmap.recycle();
        bitmap = null;
    }
    return scaleBitmap;
}

}

/**

  • 传入Bitmap和图片的Url名字,判断系统是否旋转过图片,如果旋转过则纠正
  • @param Bitmap
  • @param String
  • @return Bitmap
    */
    public static Bitmap changeRotation(Bitmap bmp,String path){
    CompareActivity.IS_ROTATION = false;
    int degree = 0;
    ExifInterface exifInterface;
    try {
    exifInterface = new ExifInterface(path);
    int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,-1);
    switch (tag) {
    case ExifInterface.ORIENTATION_ROTATE_90:
    degree = 90;
    CompareActivity.IS_ROTATION = true;
    break;
    case ExifInterface.ORIENTATION_ROTATE_180:
    degree = 180;
    CompareActivity.IS_ROTATION = true;
    break;
    case ExifInterface.ORIENTATION_ROTATE_270:
    degree = 270;
    CompareActivity.IS_ROTATION = true;
    break;
    default:
    break;
    }
    Matrix matrix = new Matrix();
    matrix.postRotate(degree);
    if (bmp != null){
    bmp = Bitmap.createBitmap(bmp,bmp.getWidth(),bmp.getHeight(),true);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    return bmp;
    }

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...