android 对已知路径下图片进行压缩

用户有很多对图片最大内存进行限制的需求,当图片宽高小于已定标准的宽高时,不对图片做处理,当图片宽高大雨已定标准的宽高时,对图片宽高进行赋值,使大图片满足压缩后满足要求,同时保证不对清晰度小的图片进行处理

 int maxWidth=624,maxHeight=840;//定义目标图片的最大宽高,若原图高于这个数值,直接赋值为以上的数值
        Bitmap bitmap= BitmapFactory.decodeFile(path);
        int originWidth=bitmap.getWidth();
        int originHeight=bitmap.getHeight();
        if(originWidthreturn ;
        }
        int width=originWidth;
        int height=originHeight;

        if(originWidth>maxWidth) {
            width=maxWidth;
            double i = originWidth * 1.0 / maxWidth;
            height = (int) Math.floor(originHeight / i);
            bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

        }
        if(height>maxHeight){
            height=maxHeight;
            bitmap=Bitmap.createBitmap(bitmap,0,0,width,height);
        }
        File file=new File(path);
        if(file.exists()){
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();

        } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }

你可能感兴趣的:(Android)