您的位置:首页 > 移动开发 > Android开发

android如何把Res目录下的一张图片保存到本地

2016-02-26 09:33 495 查看
[code]/**
 * res目录下面的一张图片保存到本地
 * @param id    图片的id
 */
private void saveImage(int id) {
    // getFilesDir().getAbsolutePath()+"/image"\
    //在本地创建一个文件夹
    File file = new File(getFilesDir().getAbsolutePath() + "/image");
    // File absoluteFile = getFilesDir().getAbsoluteFile();
    //判断本地是否存在,防止每次启动App都要创建
    if (file.exists()) {
        return;
    }
    Log.i(TAG, "----------------------------------------------------------------");
    //使用BitmapFactory把res下的图片转换成Bitmap对象
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);//把图片从res下面转一个bitmap
    FileOutputStream fos = null;
    try {
    //获得一个可写的输入流
        fos = openFileOutput("image", Context.MODE_PRIVATE);
     //使用图片压缩对图片进行处理  压缩的格式  可以是JPEG、PNG、WEBP   第二个参数是图片的压缩比例,第三个参数是写入流
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Log.i(TAG, "绝对路径" + getFilesDir().getAbsolutePath() + "/image");
}


读取转换成bitmap对象设置到控件上面

Bitmap decodeFile = BitmapFactory.decodeFile(getFilesDir().getAbsolutePath()+”/image”);

存取图片也可以使用以下的方式 (转载)

public class MainActivity extends Activity {

[code]@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    Bitmap bmp = BitmapFactory.decodeFile("/mnt/sdcard/wolf.jpg");  

        ImageView mv = (ImageView)findViewById(R.id.img);  
        mv.setImageBitmap(bmp);  

        File file = null;  
        try {  
            file = new File("/mnt/sdcard/wolf_tmp.jpg");  
            file.delete();  
            ByteArrayOutputStream stream = new ByteArrayOutputStream();  
            bmp.compress(CompressFormat.JPEG, 100, stream);  

            FileOutputStream os = new FileOutputStream(file);  
            os.write(stream.toByteArray());  
            os.close();  
        } catch (Exception ex) {  
            file = null;  
        }  

        bmp = BitmapFactory.decodeFile("/mnt/sdcard/wolf_tmp.jpg");  

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: