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

/**
 * 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);
    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 {

@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");  


}  
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值