Android实现下载图片并保存到SD卡中()

2024-06-18 02:08

本文主要是介绍Android实现下载图片并保存到SD卡中(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文地址  http://blog.csdn.net/ameyume/article/details/6528205

1.java代码,下载图片的主程序

先实现显示图片,然后点击下载图片按钮,执行下载功能。

从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。

(1)ICS4.0及更高版本中的实现

4.0中不允许在主线程,即UI线程中操作网络,所以必须新开一个线程,在子线程中执行网络连接;然后在主线程中显示图片。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class IcsTestActivity extends Activity {  
  2.   
  3.     private final static String TAG = "IcsTestActivity";  
  4.     private final static String ALBUM_PATH  
  5.             = Environment.getExternalStorageDirectory() + "/download_test/";  
  6.     private ImageView mImageView;  
  7.     private Button mBtnSave;  
  8.     private ProgressDialog mSaveDialog = null;  
  9.     private Bitmap mBitmap;  
  10.     private String mFileName;  
  11.     private String mSaveMessage;  
  12.   
  13.   
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.   
  19.         mImageView = (ImageView)findViewById(R.id.imgSource);  
  20.         mBtnSave = (Button)findViewById(R.id.btnSave);  
  21.   
  22.         new Thread(connectNet).start();  
  23.   
  24.         // 下载图片  
  25.         mBtnSave.setOnClickListener(new Button.OnClickListener(){  
  26.             public void onClick(View v) {  
  27.                 mSaveDialog = ProgressDialog.show(IcsTestActivity.this"保存图片""图片正在保存中,请稍等..."true);  
  28.                 new Thread(saveFileRunnable).start();  
  29.         }  
  30.         });  
  31.     }  
  32.   
  33.     /** 
  34.      * Get image from newwork 
  35.      * @param path The path of image 
  36.      * @return byte[] 
  37.      * @throws Exception 
  38.      */  
  39.     public byte[] getImage(String path) throws Exception{  
  40.         URL url = new URL(path);  
  41.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  42.         conn.setConnectTimeout(5 * 1000);  
  43.         conn.setRequestMethod("GET");  
  44.         InputStream inStream = conn.getInputStream();  
  45.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
  46.             return readStream(inStream);  
  47.         }  
  48.         return null;  
  49.     }  
  50.   
  51.     /** 
  52.      * Get image from newwork 
  53.      * @param path The path of image 
  54.      * @return InputStream 
  55.      * @throws Exception 
  56.      */  
  57.     public InputStream getImageStream(String path) throws Exception{  
  58.         URL url = new URL(path);  
  59.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  60.         conn.setConnectTimeout(5 * 1000);  
  61.         conn.setRequestMethod("GET");  
  62.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
  63.             return conn.getInputStream();  
  64.         }  
  65.         return null;  
  66.     }  
  67.     /** 
  68.      * Get data from stream 
  69.      * @param inStream 
  70.      * @return byte[] 
  71.      * @throws Exception 
  72.      */  
  73.     public static byte[] readStream(InputStream inStream) throws Exception{  
  74.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  75.         byte[] buffer = new byte[1024];  
  76.         int len = 0;  
  77.         while( (len=inStream.read(buffer)) != -1){  
  78.             outStream.write(buffer, 0, len);  
  79.         }  
  80.         outStream.close();  
  81.         inStream.close();  
  82.         return outStream.toByteArray();  
  83.     }  
  84.   
  85.     /** 
  86.      * 保存文件 
  87.      * @param bm 
  88.      * @param fileName 
  89.      * @throws IOException 
  90.      */  
  91.     public void saveFile(Bitmap bm, String fileName) throws IOException {  
  92.         File dirFile = new File(ALBUM_PATH);  
  93.         if(!dirFile.exists()){  
  94.             dirFile.mkdir();  
  95.         }  
  96.         File myCaptureFile = new File(ALBUM_PATH + fileName);  
  97.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
  98.         bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
  99.         bos.flush();  
  100.         bos.close();  
  101.     }  
  102.   
  103.     private Runnable saveFileRunnable = new Runnable(){  
  104.         @Override  
  105.         public void run() {  
  106.             try {  
  107.                 saveFile(mBitmap, mFileName);  
  108.                 mSaveMessage = "图片保存成功!";  
  109.             } catch (IOException e) {  
  110.                 mSaveMessage = "图片保存失败!";  
  111.                 e.printStackTrace();  
  112.             }  
  113.             messageHandler.sendMessage(messageHandler.obtainMessage());  
  114.         }  
  115.   
  116.     };  
  117.   
  118.     private Handler messageHandler = new Handler() {  
  119.         @Override  
  120.         public void handleMessage(Message msg) {  
  121.             mSaveDialog.dismiss();  
  122.             Log.d(TAG, mSaveMessage);  
  123.             Toast.makeText(IcsTestActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();  
  124.         }  
  125.     };  
  126.   
  127.     /* 
  128.      * 连接网络 
  129.      * 由于在4.0中不允许在主线程中访问网络,所以需要在子线程中访问 
  130.      */  
  131.     private Runnable connectNet = new Runnable(){  
  132.         @Override  
  133.         public void run() {  
  134.             try {  
  135.                 String filePath = "https://img-my.csdn.net/uploads/201402/24/1393242467_3999.jpg";  
  136.                 mFileName = "test.jpg";  
  137.   
  138.                 //以下是取得图片的两种方法  
  139.                  方法1:取得的是byte数组, 从byte数组生成bitmap  
  140.                 byte[] data = getImage(filePath);  
  141.                 if(data!=null){  
  142.                     mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap  
  143.                 }else{  
  144.                     Toast.makeText(IcsTestActivity.this"Image error!"1).show();  
  145.                 }  
  146.                   
  147.   
  148.                 //******** 方法2:取得的是InputStream,直接从InputStream生成bitmap ***********/  
  149.                 mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));  
  150.                 //********************************************************************/  
  151.   
  152.                 // 发送消息,通知handler在主线程中更新UI  
  153.                 connectHanlder.sendEmptyMessage(0);  
  154.                 Log.d(TAG, "set image ...");  
  155.             } catch (Exception e) {  
  156.                 Toast.makeText(IcsTestActivity.this,"无法链接网络!"1).show();  
  157.                 e.printStackTrace();  
  158.             }  
  159.   
  160.         }  
  161.   
  162.     };  
  163.   
  164.     private Handler connectHanlder = new Handler() {  
  165.         @Override  
  166.         public void handleMessage(Message msg) {  
  167.             Log.d(TAG, "display image");  
  168.             // 更新UI,显示图片  
  169.             if (mBitmap != null) {  
  170.                 mImageView.setImageBitmap(mBitmap);// display image  
  171.             }  
  172.         }  
  173.     };  
  174.   
  175. }  
(2)2.3以及以下版本可以在主线程中操作网络连接,但最好不要这样做,因为连接网络是阻塞的,如果5秒钟还没有连接上,就会引起ANR。

[java]  view plain copy
  1. public class AndroidTest2_3_3 extends Activity {  
  2.     private final static String TAG = "AndroidTest2_3_3";  
  3.     private final static String ALBUM_PATH   
  4.             = Environment.getExternalStorageDirectory() + "/download_test/";  
  5.     private ImageView imageView;  
  6.     private Button btnSave;  
  7.     private ProgressDialog myDialog = null;  
  8.     private Bitmap bitmap;  
  9.     private String fileName;  
  10.     private String message;  
  11.       
  12.       
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);  
  17.           
  18.         imageView = (ImageView)findViewById(R.id.imgSource);  
  19.         btnSave = (Button)findViewById(R.id.btnSave);  
  20.           
  21.         String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";  
  22.         fileName = "test.jpg";  
  23.           
  24.         try {  
  25.              取得的是byte数组, 从byte数组生成bitmap  
  26.             byte[] data = getImage(filePath);        
  27.             if(data!=null){        
  28.                 bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap        
  29.                 imageView.setImageBitmap(bitmap);// display image        
  30.             }else{        
  31.                 Toast.makeText(AndroidTest2_3_3.this"Image error!"1).show();        
  32.             }  
  33.               
  34.   
  35.             //******** 取得的是InputStream,直接从InputStream生成bitmap ***********/  
  36.             bitmap = BitmapFactory.decodeStream(getImageStream(filePath));  
  37.             if (bitmap != null) {  
  38.                 imageView.setImageBitmap(bitmap);// display image  
  39.             }  
  40.             //********************************************************************/  
  41.             Log.d(TAG, "set image ...");  
  42.         } catch (Exception e) {     
  43.             Toast.makeText(AndroidTest2_3_3.this,"Newwork error!"1).show();     
  44.             e.printStackTrace();     
  45.         }     
  46.   
  47.           
  48.         // 下载图片  
  49.         btnSave.setOnClickListener(new Button.OnClickListener(){  
  50.             public void onClick(View v) {  
  51.                 myDialog = ProgressDialog.show(AndroidTest2_3_3.this"保存图片""图片正在保存中,请稍等..."true);  
  52.                 new Thread(saveFileRunnable).start();  
  53.         }  
  54.         });  
  55.     }  
  56.   
  57.     /**   
  58.      * Get image from newwork   
  59.      * @param path The path of image   
  60.      * @return byte[] 
  61.      * @throws Exception   
  62.      */    
  63.     public byte[] getImage(String path) throws Exception{     
  64.         URL url = new URL(path);     
  65.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();     
  66.         conn.setConnectTimeout(5 * 1000);     
  67.         conn.setRequestMethod("GET");     
  68.         InputStream inStream = conn.getInputStream();     
  69.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){     
  70.             return readStream(inStream);     
  71.         }     
  72.         return null;     
  73.     }     
  74.     
  75.     /**   
  76.      * Get image from newwork   
  77.      * @param path The path of image   
  78.      * @return InputStream 
  79.      * @throws Exception   
  80.      */  
  81.     public InputStream getImageStream(String path) throws Exception{     
  82.         URL url = new URL(path);     
  83.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();     
  84.         conn.setConnectTimeout(5 * 1000);     
  85.         conn.setRequestMethod("GET");  
  86.         if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){     
  87.             return conn.getInputStream();        
  88.         }     
  89.         return null;   
  90.     }  
  91.     /**   
  92.      * Get data from stream  
  93.      * @param inStream   
  94.      * @return byte[] 
  95.      * @throws Exception   
  96.      */    
  97.     public static byte[] readStream(InputStream inStream) throws Exception{     
  98.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();     
  99.         byte[] buffer = new byte[1024];     
  100.         int len = 0;     
  101.         while( (len=inStream.read(buffer)) != -1){     
  102.             outStream.write(buffer, 0, len);     
  103.         }     
  104.         outStream.close();     
  105.         inStream.close();     
  106.         return outStream.toByteArray();     
  107.     }   
  108.   
  109.     /** 
  110.      * 保存文件 
  111.      * @param bm 
  112.      * @param fileName 
  113.      * @throws IOException 
  114.      */  
  115.     public void saveFile(Bitmap bm, String fileName) throws IOException {  
  116.         File dirFile = new File(ALBUM_PATH);  
  117.         if(!dirFile.exists()){  
  118.             dirFile.mkdir();  
  119.         }  
  120.         File myCaptureFile = new File(ALBUM_PATH + fileName);  
  121.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
  122.         bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
  123.         bos.flush();  
  124.         bos.close();  
  125.     }  
  126.       
  127.     private Runnable saveFileRunnable = new Runnable(){  
  128.         @Override  
  129.         public void run() {  
  130.             try {  
  131.                 saveFile(bitmap, fileName);  
  132.                 message = "图片保存成功!";  
  133.             } catch (IOException e) {  
  134.                 message = "图片保存失败!";  
  135.                 e.printStackTrace();  
  136.             }  
  137.             messageHandler.sendMessage(messageHandler.obtainMessage());  
  138.         }  
  139.               
  140.     };  
  141.       
  142.     private Handler messageHandler = new Handler() {  
  143.         @Override  
  144.         public void handleMessage(Message msg) {  
  145.             myDialog.dismiss();  
  146.             Log.d(TAG, message);  
  147.             Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show();  
  148.         }  
  149.     };  
  150. }  

  

下载进度条的可以参考我的另外一个帖子:Android更新下载进度条

 

2.main.xml文件,只有一个button和一个ImageView

[xhtml]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <Button  
  8.         android:id="@+id/btnSave"  
  9.         android:layout_width="wrap_content"   
  10.         android:layout_height="wrap_content"  
  11.         android:text="保存图片"  
  12.         />  
  13.     <ImageView  
  14.         android:id="@+id/imgSource"  
  15.         android:layout_width="wrap_content"   
  16.         android:layout_height="wrap_content"   
  17.         android:adjustViewBounds="true"  
  18.         />  
  19. </LinearLayout>  

3.在mainfest文件中增加互联网权限和写sd卡的权限

[xhtml]  view plain copy
  1. <uses-permission android:name="android.permission.INTERNET" />   
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  3.    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  

4.预览图:

注:本实例图片是本人拍摄的位于东京西郊美军横田基地的一个大门。

横田基地的图片已经删除,所以无法加载。更新了我空间相册的另外一张图,此图较小,所以保存时很快,“图片正在保存中,请稍等...”的画面会一闪而过。

在4.2.1魅族mx3真机上验证如下:

这篇关于Android实现下载图片并保存到SD卡中()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1071012

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja