首页 / ANDROID / Android中图片的文件储存
Android中图片的文件储存
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Android中图片的文件储存,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2085字,纯文字阅读大概需要3分钟。
内容图文
![Android中图片的文件储存](/upload/InfoBanner/zyjiaocheng/1329/016eb1b885b7469488ee995eb3eefadc.jpg)
两种常见情况。1、储存一个bitmap,2、直接下载一个图片并储存。
1、将一个bitmap存成文件
public static void saveMyBitmap(Bitmap mBitmap, String fileName) { // 新建文件 File f = new File(fileName); // 新建文件输出流 FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } // 将bitmap压缩至文件输出流 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } }
其中,核心的方法就是Bitmap类中的compress方法。
public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream) { thrownew RuntimeException("Stub!"); }
这个方法有三个参数,第一个参数是压缩格式,第二个是压缩质量(最大是100),第三个是文件输出流。
public static enum CompressFormat { JPEG, PNG, WEBP; private CompressFormat() { } }
由上面代码易知,图片可以选择三种格式压缩。
2、直接下载一个图片并储存
public class DownloadTask extends AsyncTask<String, Integer , String> { Context context; public DownloadTask(Context context){ this.context = context; } @Override protected String doInBackground(String... strings) { // 文件的下载地址 String fileUrl = strings[0]; // 文件名 String fileName = strings[1]; // 文件的扩展名 String expandName = strings[2]; try { // 下载图片 URL u = new URL(fileUrl); InputStream is = u.openStream(); DataInputStream dis = new DataInputStream(is); // 保存图片文件byte[] buffer = newbyte[1024]; int length; FileOutputStream fos = new FileOutputStream(new File(fileName + expandName)); while ((length = dis.read(buffer))>0) { fos.write(buffer, 0, length); } // 扫描指定文件使媒体更新 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(new File(fileName + expandName)); intent.setData(uri); context.sendBroadcast(intent); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SecurityException se) { se.printStackTrace(); } return (fileName+expandName); } @Override protectedvoid onPostExecute(String fileName) { UIUtil.toastMessage(context, "下载成功,图片已保存至:" + fileName); }
Done
原文:http://www.cnblogs.com/fishbone-lsy/p/4862484.html
内容总结
以上是互联网集市为您收集整理的Android中图片的文件储存全部内容,希望文章能够帮你解决Android中图片的文件储存所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。