ANDROID 實現圖片保存

1.java代碼,下載圖片的主程序html

先實現顯示圖片,而後點擊下載圖片按鈕,執行下載功能。java

從網絡上取得的圖片,生成Bitmap時有兩種方法,一種是先轉換爲byte[],再生成bitmap;一種是直接用InputStream生成bitmap。android

(1)ICS4.0及更高版本中的實現數組

4.0中不容許在主線程,即UI線程中操做網絡,因此必須新開一個線程,在子線程中執行網絡鏈接;而後在主線程中顯示圖片。網絡

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片ide

public class IcsTestActivity extends Activity {  
  
    private final static String TAG = "IcsTestActivity";  
    private final static String ALBUM_PATH  
            = Environment.getExternalStorageDirectory() + "/download_test/";  
    private ImageView mImageView;  
    private Button mBtnSave;  
    private ProgressDialog mSaveDialog = null;  
    private Bitmap mBitmap;  
    private String mFileName;  
    private String mSaveMessage;  
  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
  
        mImageView = (ImageView)findViewById(R.id.imgSource);  
        mBtnSave = (Button)findViewById(R.id.btnSave);  
  
        new Thread(connectNet).start();  
  
        // 下載圖片  
        mBtnSave.setOnClickListener(new Button.OnClickListener(){  
            public void onClick(View v) {  
                mSaveDialog = ProgressDialog.show(IcsTestActivity.this, "保存圖片", "圖片正在保存中,請稍等...", true);  
                new Thread(saveFileRunnable).start();  
        }  
        });  
    }  
  
    /** 
     * Get image from newwork 
     * @param path The path of image 
     * @return byte[] 
     * @throws Exception 
     */  
    public byte[] getImage(String path) throws Exception{  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setConnectTimeout(5 * 1000);  
        conn.setRequestMethod("GET");  
        InputStream inStream = conn.getInputStream();  
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
            return readStream(inStream);  
        }  
        return null;  
    }  
  
    /** 
     * Get image from newwork 
     * @param path The path of image 
     * @return InputStream 
     * @throws Exception 
     */  
    public InputStream getImageStream(String path) throws Exception{  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setConnectTimeout(5 * 1000);  
        conn.setRequestMethod("GET");  
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
            return conn.getInputStream();  
        }  
        return null;  
    }  
    /** 
     * Get data from stream 
     * @param inStream 
     * @return byte[] 
     * @throws Exception 
     */  
    public static byte[] readStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1){  
            outStream.write(buffer, 0, len);  
        }  
        outStream.close();  
        inStream.close();  
        return outStream.toByteArray();  
    }  
  
    /** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public void saveFile(Bitmap bm, String fileName) throws IOException {  
        File dirFile = new File(ALBUM_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        File myCaptureFile = new File(ALBUM_PATH + fileName);  
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
        bos.flush();  
        bos.close();  
    }  
  
    private Runnable saveFileRunnable = new Runnable(){  
        @Override  
        public void run() {  
            try {  
                saveFile(mBitmap, mFileName);  
                mSaveMessage = "圖片保存成功!";  
            } catch (IOException e) {  
                mSaveMessage = "圖片保存失敗!";  
                e.printStackTrace();  
            }  
            messageHandler.sendMessage(messageHandler.obtainMessage());  
        }  
  
    };  
  
    private Handler messageHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            mSaveDialog.dismiss();  
            Log.d(TAG, mSaveMessage);  
            Toast.makeText(IcsTestActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();  
        }  
    };  
  
    /* 
     * 鏈接網絡 
     * 因爲在4.0中不容許在主線程中訪問網絡,因此須要在子線程中訪問 
     */  
    private Runnable connectNet = new Runnable(){  
        @Override  
        public void run() {  
            try {  
                String filePath = "http://img.my.csdn.net/uploads/201402/24/1393242467_3999.jpg";  
                mFileName = "test.jpg";  
  
                //如下是取得圖片的兩種方法  
                //////////////// 方法1:取得的是byte數組, 從byte數組生成bitmap  
                byte[] data = getImage(filePath);  
                if(data!=null){  
                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap  
                }else{  
                    Toast.makeText(IcsTestActivity.this, "Image error!", 1).show();  
                }  
                ////////////////////////////////////////////////////////  
  
                //******** 方法2:取得的是InputStream,直接從InputStream生成bitmap ***********/  
                mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));  
                //********************************************************************/  
  
                // 發送消息,通知handler在主線程中更新UI  
                connectHanlder.sendEmptyMessage(0);  
                Log.d(TAG, "set image ...");  
            } catch (Exception e) {  
                Toast.makeText(IcsTestActivity.this,"沒法連接網絡!", 1).show();  
                e.printStackTrace();  
            }  
  
        }  
  
    };  
  
    private Handler connectHanlder = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            Log.d(TAG, "display image");  
            // 更新UI,顯示圖片  
            if (mBitmap != null) {  
                mImageView.setImageBitmap(mBitmap);// display image  
            }  
        }  
    };  
  
}

(2)2.3以及如下版本能夠在主線程中操做網絡鏈接,但最好不要這樣作,由於鏈接網絡是阻塞的,若是5秒鐘尚未鏈接上,就會引發ANR。this

[java] view plaincopyurl

public class AndroidTest2_3_3 extends Activity {  
    private final static String TAG = "AndroidTest2_3_3";  
    private final static String ALBUM_PATH   
            = Environment.getExternalStorageDirectory() + "/download_test/";  
    private ImageView imageView;  
    private Button btnSave;  
    private ProgressDialog myDialog = null;  
    private Bitmap bitmap;  
    private String fileName;  
    private String message;  
      
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        imageView = (ImageView)findViewById(R.id.imgSource);  
        btnSave = (Button)findViewById(R.id.btnSave);  
          
        String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";  
        fileName = "test.jpg";  
          
        try {  
            //////////////// 取得的是byte數組, 從byte數組生成bitmap  
            byte[] data = getImage(filePath);        
            if(data!=null){        
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap        
                imageView.setImageBitmap(bitmap);// display image        
            }else{        
                Toast.makeText(AndroidTest2_3_3.this, "Image error!", 1).show();        
            }  
            ////////////////////////////////////////////////////////  
  
            //******** 取得的是InputStream,直接從InputStream生成bitmap ***********/  
            bitmap = BitmapFactory.decodeStream(getImageStream(filePath));  
            if (bitmap != null) {  
                imageView.setImageBitmap(bitmap);// display image  
            }  
            //********************************************************************/  
            Log.d(TAG, "set image ...");  
        } catch (Exception e) {     
            Toast.makeText(AndroidTest2_3_3.this,"Newwork error!", 1).show();     
            e.printStackTrace();     
        }     
  
          
        // 下載圖片  
        btnSave.setOnClickListener(new Button.OnClickListener(){  
            public void onClick(View v) {  
                myDialog = ProgressDialog.show(AndroidTest2_3_3.this, "保存圖片", "圖片正在保存中,請稍等...", true);  
                new Thread(saveFileRunnable).start();  
        }  
        });  
    }  
  
    /**   
     * Get image from newwork   
     * @param path The path of image   
     * @return byte[] 
     * @throws Exception   
     */    
    public byte[] getImage(String path) throws Exception{     
        URL url = new URL(path);     
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();     
        conn.setConnectTimeout(5 * 1000);     
        conn.setRequestMethod("GET");     
        InputStream inStream = conn.getInputStream();     
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){     
            return readStream(inStream);     
        }     
        return null;     
    }     
    
    /**   
     * Get image from newwork   
     * @param path The path of image   
     * @return InputStream 
     * @throws Exception   
     */  
    public InputStream getImageStream(String path) throws Exception{     
        URL url = new URL(path);     
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();     
        conn.setConnectTimeout(5 * 1000);     
        conn.setRequestMethod("GET");  
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){     
            return conn.getInputStream();        
        }     
        return null;   
    }  
    /**   
     * Get data from stream  
     * @param inStream   
     * @return byte[] 
     * @throws Exception   
     */    
    public static byte[] readStream(InputStream inStream) throws Exception{     
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();     
        byte[] buffer = new byte[1024];     
        int len = 0;     
        while( (len=inStream.read(buffer)) != -1){     
            outStream.write(buffer, 0, len);     
        }     
        outStream.close();     
        inStream.close();     
        return outStream.toByteArray();     
    }   
  
    /** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public void saveFile(Bitmap bm, String fileName) throws IOException {  
        File dirFile = new File(ALBUM_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        File myCaptureFile = new File(ALBUM_PATH + fileName);  
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
        bos.flush();  
        bos.close();  
    }  
      
    private Runnable saveFileRunnable = new Runnable(){  
        @Override  
        public void run() {  
            try {  
                saveFile(bitmap, fileName);  
                message = "圖片保存成功!";  
            } catch (IOException e) {  
                message = "圖片保存失敗!";  
                e.printStackTrace();  
            }  
            messageHandler.sendMessage(messageHandler.obtainMessage());  
        }  
              
    };  
      
    private Handler messageHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            myDialog.dismiss();  
            Log.d(TAG, message);  
            Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show();  
        }  
    };  
}

下載進度條的能夠參考個人另一個帖子:Android更新下載進度條.net

2.main.xml文件,只有一個button和一個ImageView線程

[xhtml] view plaincopy

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
    <Button  
        android:id="@+id/btnSave"  
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"  
        android:text="保存圖片"  
        />  
    <ImageView  
        android:id="@+id/imgSource"  
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"   
        android:adjustViewBounds="true"  
        />  
</LinearLayout>

3.在mainfest文件中增長互聯網權限和寫sd卡的權限

[xhtml] view plaincopy

<uses-permission android:name="android.permission.INTERNET" />   
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
   <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
相關文章
相關標籤/搜索