[转] BItmap图片预览缩放等操作综合资料(待检验)

BItmap图片预览缩放等操作综合资料(待检验)

目标:从sdcard中读取图片,并按一定的比例进行缩放,并保存到应用程序的目录下,同时通过ImageView显示的图片
分析:
android的文件系统与Linux的文件系统是一致的,但是出于一种安全的考虑,应用程序不能随意地创建文件和目录,也就是说应用程序不能随意跨越自己程序的边界,因此,应用程序一般只允许在自身程序的目录下才能进行自由的文件操作。通过Eclipse的DDMS视图可以看到android的应用程序的位置是 /data/data/,而文件则保存在 /data/data//files/目录下。
至于图片压缩,简单是说是按图片按比例进行缩放,android貌似只提供了一个android.graphics.Bitmap类来进行图片处理,所有的格式(png jpg gif)都可以用Bitmap来表示和存储。
Java代码 
public void WriteFileEx() {
        try {

                //获取源图片的大小

                Bitmap bm;

                BitmapFactory.Options opts = new BitmapFactory.Options();

                //当opts不为null时,但decodeFile返回空,不为图片分配内存,只获取图片的大小,并保存在opts的outWidth和outHeight

                BitmapFactory.decodeFile("/sdcard/Stephen.jpg" opts);

                int srcWidth = opts.outWidth;

                int srcHeight = opts.outHeight;

                int destWidth = 0;

                int destHeight = 0;

                double ratio = 0.0;                //缩放的比例

                tvInfo.setText("Width:" + srcWidth + " Height:" + srcHeight);  //tvInfo是一个TextView用于显示图片的尺寸信息

                //按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度

                if(srcWidth >srcHeight) {

                ratio = srcWidth / maxLength;

                destWidth = maxLength;

                destHeight = (int) (srcHeight / ratio);

                }else {

                        ratio = srcHeight / maxLength;

                        destHeight = maxLength;

                        destWidth = (int) (srcWidth / ratio); 

                }

                //对图片进行压缩,是在读取的过程中进行压缩,而不是把图片读进了内存再进行压缩

                BitmapFactory.Options newOpts = new BitmapFactory.Options();

                //缩放的比例,缩放是很难按准备的比例进行缩放的,目前我只发现只能通过inSampleSize来进行缩放,其值表明缩放的倍数,SDK中建议其值是2的指数值

                newOpts.inSampleSize = (int) ratio + 1;

                //inJustDecodeBounds设为false表示把图片读进内存中

                newOpts.inJustDecodeBounds = false;

                //设置大小,这个一般是不准确的,是以inSampleSize的为准,但是如果不设置却不能缩放

                newOpts.outHeight = destHeight;

                newOpts.outWidth = destWidth;

                //添加尺寸信息,

                tvInfo.append("\nWidth:" + newOpts.outWidth + " Height:" + newOpts.outHeight);

                //获取缩放后图片

                Bitmap destBm = BitmapFactory.decodeFile("/sdcard/Stephen.jpg" newOpts);



                if(destBm == null) {

                        showAlert("CreateFile" 0 "Create Failed" "OK" false);

                } else {

                        //文件命名,通过GUID可避免命名的重复
        
                        String fileName = java.util.UUID.randomUUID().toString() + ".jpg";

                        //另外定义:

                        //ConfigManager.photoDir = getFileStreamPath(photoDirName) 
        
                        //String photoDirName = "photo";要注意是根目录

                        File destFile = new File(ConfigManager.photoDir fileName);

                        //创建文件输出流

                        OutputStream os = new FileOutputStream(destFile);

                        //存储

                        destBm.compress(CompressFormat.JPEG 100 os);

                        os.close();

                        //显示图片

                        //setImgView(fileName);
        
                        //setDrawable(fileName);
        
                        setDrawableAbsolute(fileName);

                }

        } catch(Exception e) {

                showAlert("CreateFile" 0 e.toString() "OK" false);

        }

}
Java代码
Java代码
显示图片有多种方式,通过ImageView,可以用Bitmap或者是用Drawable来进行显示。下面的imgView是一个ImageView的引用。

Bitmap通过输入流的方式显示:

public void setImgView(String fileName) {

try{

        File file = new File(ConfigManager.photoDir fileName);

        InputStream is = new FileInputStream(file);

        Bitmap bm = BitmapFactory.decodeStream(is);

        if (bm != null) {

                imgView.setImageBitmap(bm);

        } else {

                showAlert("CreateFile" 0 "Set Failed" "OK" false);

        }

        is.close();

} catch(Exception e) {

        showAlert("CreateFile" 0 e.toString() "OK" false);

}

}
Java代码Drawable通过输入流的方式显示:

public void setDrawable(String fileName) {

try {

        File file = new File(ConfigManager.photoDir fileName);

        InputStream is = new FileInputStream(file);

        Drawable da = Drawable.createFromStream(is null);

        if (da != null) {

        imgView.setImageDrawable(da);

        } else {

                showAlert("CreateFile" 0 "Set Failed" "OK" false);

        }

        is.close();

} catch(Exception e) {

        showAlert("CreateFile" 0 e.toString() "OK" false);

}

}

直接通过Drawable进行显示:

public void setDrawableAbsolute(String fileName) {

try {

        File file = new File(ConfigManager.photoDir fileName);

        Drawable da = Drawable.createFromPath(file.getAbsolutePath());

        if (da != null) {

                imgView.setImageDrawable(da);

        } else {

                showAlert("CreateFile" 0 "Set Failed" "OK" false);

        }

} catch(Exception e) {

        showAlert("CreateFile" 0 e.toString() "OK" false);

}

}<span style="font-size: small;"><font size="3"><font><font size="3"><p class="MsoNormal"> </p></font></font></font></span>总的来说,在应用程序的作用域范围内android还是可以比较灵活地进行文件操作,不过可能显示地通过流的方式来操作应该会对程序的性能有一定的影响。在进行具体操作的时候要注意

相对路径和绝对路径的区别,如果获得了应用程序的作用域中的相对路径,可以通过File.getAbsolutePath()的方法来获取完整的绝对路径来进行操作。

=======================================================================

 

在开发图片浏览器等软件是,很多时候要显示图片的缩略图,而一般情况下,我们要将图片按照固定大小取缩略图,一般取缩略图的方法是使用BitmapFactory的decodeFile方法,然后通过传递进去 BitmapFactory.Option类型的参数进行取缩略图,在Option中,属性值inSampleSize表示缩略图大小为原始图片大小的几分之一,即如果这个值为2,则取出的缩略图的宽和高都是原始图片的1/2,图片大小就为原始大小的1/4。Java代码

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=20;
options.inTempStorage = new byte; //16MB的临时存储空间
Bitmap bitMap = BitmapFactory.decodeFile(path,options); 
selectImage.setImageBitmap(bitMap);然而,如果我们想取固定大小的缩略图就比较困难了,比如,我们想将不同大小的图片去出来的缩略图高度都为200px,而且要保证图片不失真,那怎么办?我们总不能将原始图片加载到内存中再进行缩放处理吧,要知道在移动开发中,内存是相当宝贵的,而且一张100K的图片,加载完所占用的内存何止 100K?

  经过研究,发现,Options中有个属性inJustDecodeBounds,研究了一下,终于明白是什么意思了,SDK中的E文是这么说的

  If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

  意思就是说如果该值设为true那么将不返回实际的bitmap不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息,那么相应的方法也就出来了,通过设置inJustDecodeBounds为true,获取到outHeight(图片原始高度)和 outWidth(图片的原始宽度),然后计算一个inSampleSize(缩放值),然后就可以取图片了,这里要注意的是,inSampleSize 可能小于0,必须做判断。
具体代码如下:
Java代码
FrameLayout fr=(FrameLayout)findViewById(R.id.FrameLayout01);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/test.jpg", options); //此时返回bm为空
        options.inJustDecodeBounds = false;
         //缩放比
        int be = (int)(options.outHeight / (float)200);
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;
        //重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
        bitmap=BitmapFactory.decodeFile("/sdcard/test.jpg",options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        System.out.println(w+"   "+h);
        ImageView iv=new ImageView(this);
        iv.setImageBitmap(bitmap);

这样我们就可以读取较大的图片而不会内存溢出了。如果你想把压缩后的图片保存在Sdcard上的话就很简单了:
File file=new File("/sdcard/feng.png");
        try {
            FileOutputStream out=new FileOutputStream(file);
            if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, 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();
        }
ok,这样就把图片保存在/sdcard/feng.png这个文件里面了,呵呵。
但是这里的缩放保存是按长宽比例的,下边也可以按固定大小缩放哦:



Java代码
int bmpWidth  = bitmap.getWidth();  

        int bmpHeight = bitmap.getHeight();  

          

        //缩放图片的尺寸  

        float scaleWidth  = (float) sWidth / bmpWidth;     //按固定大小缩放  sWidth 写多大就多大

        float scaleHeight = (float) sHeight / bmpHeight;  //

        Matrix matrix = new Matrix();  

        matrix.postScale(scaleWidth, scaleHeight);  

          

        //产生缩放后的Bitmap对象  

        Bitmap resizeBitmap = Bitmap.createBitmap(  

            bitmap, 0, 0, bmpWidth, bmpHeight, matrix, false);  

        bitmap.recycle();  

                Bitmap resizeBitmap = bitmap;  

        //Bitmap to byte[]  

        byte[] photoData = bitmap2Bytes(resizeBitmap);  

        

        //save file  

        String fileName = "/sdcard/test.jpg";  

        FileUtil.writeToFile(fileName, photoData);  
Java代码
压缩图片质量:   
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);   
其中的quality为0~100, 可以压缩图片质量, 不过对于大图必须对图片resize  

这个是等比例缩放:
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

这个是截取图片某部分:
bitmap = Bitmap.createBitmap(bitmap, x, y, width, height);

这几个方法都是针对Bitmap的, 不过鉴于Bitmap可以从file中读取, 也可以写入file.  

这是我知道Android自带库里中唯一可以缩放和压缩的图片方法.

posted on 2012-05-18 21:48  fuxy  阅读(515)  评论(0编辑  收藏  举报

导航