android 下载保存图片
16lz
2021-01-26
引用:http://www.linuxidc.com/Linux/2011-06/37233.htm
1.java代码,下载图片的主程序
先实现显示图片,然后点击下载图片按钮,执行下载功能。
从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。
- publicclassAndroidTest2_3_3extendsActivity{
- privatefinalstaticStringTAG="AndroidTest2_3_3";
- privatefinalstaticStringALBUM_PATH
- =Environment.getExternalStorageDirectory()+"/download_test/";
- privateImageViewimageView;
- privateButtonbtnSave;
- privateProgressDialogmyDialog=null;
- privateBitmapbitmap;
- privateStringfileName;
- privateStringmessage;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- imageView=(ImageView)findViewById(R.id.imgSource);
- btnSave=(Button)findViewById(R.id.btnSave);
- StringfilePath="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);//displayimage
- }else{
- Toast.makeText(AndroidTest2_3_3.this,"Imageerror!",1).show();
- }
- ////////////////////////////////////////////////////////
- //********取得的是InputStream,直接从InputStream生成bitmap***********/
- bitmap=BitmapFactory.decodeStream(getImageStream(filePath));
- if(bitmap!=null){
- imageView.setImageBitmap(bitmap);//displayimage
- }
- //********************************************************************/
- Log.d(TAG,"setimage...");
- }catch(Exceptione){
- Toast.makeText(AndroidTest2_3_3.this,"Newworkerror!",1).show();
- e.printStackTrace();
- }
- //下载图片
- btnSave.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- myDialog=ProgressDialog.show(AndroidTest2_3_3.this,"保存图片","图片正在保存中,请稍等...",true);
- newThread(saveFileRunnable).start();
- }
- });
- }
- /**
- *Getimagefromnewwork
- *@parampathThepathofimage
- *@returnbyte[]
- *@throwsException
- */
- publicbyte[]getImage(Stringpath)throwsException{
- URLurl=newURL(path);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setConnectTimeout(5*1000);
- conn.setRequestMethod("GET");
- InputStreaminStream=conn.getInputStream();
- if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
- returnreadStream(inStream);
- }
- returnnull;
- }
- /**
- *Getimagefromnewwork
- *@parampathThepathofimage
- *@returnInputStream
- *@throwsException
- */
- publicInputStreamgetImageStream(Stringpath)throwsException{
- URLurl=newURL(path);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setConnectTimeout(5*1000);
- conn.setRequestMethod("GET");
- if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
- returnconn.getInputStream();
- }
- returnnull;
- }
- /**
- *Getdatafromstream
- *@paraminStream
- *@returnbyte[]
- *@throwsException
- */
- publicstaticbyte[]readStream(InputStreaminStream)throwsException{
- ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
- byte[]buffer=newbyte[1024];
- intlen=0;
- while((len=inStream.read(buffer))!=-1){
- outStream.write(buffer,0,len);
- }
- outStream.close();
- inStream.close();
- returnoutStream.toByteArray();
- }
- /**
- *保存文件
- *@parambm
- *@paramfileName
- *@throwsIOException
- */
- publicvoidsaveFile(Bitmapbm,StringfileName)throwsIOException{
- FiledirFile=newFile(ALBUM_PATH);
- if(!dirFile.exists()){
- dirFile.mkdir();
- }
- FilemyCaptureFile=newFile(ALBUM_PATH+fileName);
- BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(myCaptureFile));
- bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
- bos.flush();
- bos.close();
- }
- privateRunnablesaveFileRunnable=newRunnable(){
- @Override
- publicvoidrun(){
- try{
- saveFile(bitmap,fileName);
- message="图片保存成功!";
- }catch(IOExceptione){
- message="图片保存失败!";
- e.printStackTrace();
- }
- messageHandler.sendMessage(messageHandler.obtainMessage());
- }
- };
- privateHandlermessageHandler=newHandler(){
- @Override
- publicvoidhandleMessage(Messagemsg){
- myDialog.dismiss();
- Log.d(TAG,message);
- Toast.makeText(AndroidTest2_3_3.this,message,Toast.LENGTH_SHORT).show();
- }
- };
- }
2.main.xml文件,只有一个button和一个ImageView
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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卡的权限
- <uses-permissionAndroid:name="android.permission.INTERNET"/>
- <uses-permissionAndroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <uses-permissionAndroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
预览图:
更多相关文章
- Android之SharedPreference轻量级数据存储
- imageview 自适应各种屏幕尺寸
- Android中加载PNG图片时出现错误----No resource found
- Android中Math常用的方法,包括pow、abs、round、floor、rint、ran
- Android加载png图片时出错
- 继承Application实现Android数据共享
- 常用方法(2)------根据图片的url路径获得Bitmap对象
- android 2.2 视频和图片的缩略图处理
- Android(安卓)ImageView ScaleTypes介绍