查看Android系统图片(缩放)

本文主要展示Android系统图片的查看,选取后进行缩放后再展现

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#000000"
    >
    
    <Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="查看系统图片"
    android:id="@+id/button1"/>
    
    <ImageView android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:scaleType="fitCenter"
    android:src="@drawable/lanyan3"
    android:id="@+id/imageview1"
    android:layout_marginTop="100dp"/>
    
</LinearLayout>

MainActivity:

public class MainActivity extends Activity {
    
    private static final String SAVE_PATH = Environment.getExternalStorageDirectory() + "/lanyan/";
    private ImageView imageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        Button button = (Button) findViewById(R.id.button1);
        imageView = (ImageView)findViewById(R.id.imageview1);
        
        button.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 100);
            }
        });
        
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        
        Log.i("lanyan", "onActivityResult()");
        if (RESULT_OK != resultCode || null == data) {
            return;
        }
        //contentProvider格式
        Uri uri = data.getData();
        Log.i("lanyan", "uri: " + uri);
        String oldPath = getRealPath(uri);
        Log.i("lanyan", "realPath: " + oldPath);
        
        
        if (null != oldPath) {
            String newPath = CompressUtil.compressPic(oldPath, SAVE_PATH
                    + getFileName(oldPath));

            imageView.setImageURI(Uri.parse(newPath));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    private String getFileName(String path) {
        String name = null;
        
        if (null != path) {
            name = Uri.parse(path).getLastPathSegment();
        }
        return name;
    }
    
    /**
     * 根据Uri获取文件真实路径
     * @param uri
     * @return
     */
    private String getRealPath(Uri uri) {
        
        //此次判断仅为避免异常
        //是因为若选择的文件非图片时,则返回的URI格式为file:///....(suffix为文件真实路径)
        //有的机器上安装类似文件管理等APK时,只要通过文件管理方式选择,无论所选类型是否为图片,返回Uri都如上述形式
        //小米1,即是如此。另外某些手机则是选择非图片类型时出现上述情况
        String path = uri.toString();
        if (path.startsWith("file://")) {
            Toast.makeText(this, "地址解析异常", Toast.LENGTH_SHORT).show();
            return null;
        }
        
        //Uri格式为ContentProvider格式,content:///....(suffix非文件真实路径)
        Cursor cursor = managedQuery(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
        cursor.moveToFirst();
        
        return cursor.getString(0);
    }
    
}

CompressUtil

public class CompressUtil {
    
    /**
     * 图片压缩后的最大长/宽
     */
    private static final int PRO_MAX_SIZE = 500;
    
    public static String compressPic(String oldPath, String newPath) {
        
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //设为true,不为图片非配内存(不加载到内存中),仅获取图片原始大小,所以返回值为NULL
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(oldPath, opts);
        int srcWidth = opts.outWidth;
        int srcHeight = opts.outHeight;
        
//        Log.i("lanyan", "w:" + srcWidth + " ,h:" + srcHeight);
        
        //缩放比例
        double ratio;
        int destWidth;
        int destHeight;
        
        if (srcWidth > srcHeight) {
            destWidth = PRO_MAX_SIZE;
            ratio = (double)srcWidth / PRO_MAX_SIZE;
            destHeight = (int)(srcHeight / ratio);
        } else {
            destHeight = PRO_MAX_SIZE;
            ratio = (double)srcHeight / PRO_MAX_SIZE;
            destWidth = (int)(srcWidth / ratio);
        }
        
        Log.i("lanyan", "ratio:" + ratio );
        
        opts.inJustDecodeBounds = false;
        //缩放放图片大小以此缩放比例值为准,outWidth与outHeight未必准确
        opts.inSampleSize = (int)ratio + 1;
        opts.outWidth = destWidth;
        opts.outHeight = destHeight;
        
        Bitmap newPic = BitmapFactory.decodeFile(oldPath, opts);
        
        FileOutputStream fos = null;
        
        try {
            
            ensureDicExist(newPath);
            
            fos = new FileOutputStream(new File(newPath));
        
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i("lanyan", "获取输出流失败");
        } 
        
        newPic.compress(CompressFormat.JPEG, 100, fos);
        
        return newPath;
    }
    
    private static void ensureDicExist(String path) {
        
        int index = path.lastIndexOf("/");
        
        String newPath = path.substring(0, index);
        
        File file = new File(newPath);
        
        if(!file.exists()) {
            file.mkdirs();
        }
        
    }
    
}

注释有点乱,且没有解决选择非图片时的问题,仅仅提示了一个异常

效果图:

1,程序初始化:

2,选择一张图片(1.8M,压缩后大小为393KB)

posted @ 2012-12-13 23:11  当年明月  阅读(721)  评论(0编辑  收藏  举报