package com.example.collegehelp.tools; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by 岗哥 on 2016/10/14. */ public class DownloadPictureFromSevice { static Context context; public static String Other_People_header;//头像保存的路径 public static String myPicPath ;//头像保存的路径 static int fileLegth; static float nowPercent=0;//下载完成的比例 /* * 参数 :将要获取的服务器文件名 filename * 如果成功,返回真 */ public static boolean getOtherImageByWeb(Context context,String filename) { Other_People_header ="朋友头像保存地址";//头像保存的路径 File img = new File(Other_People_header + filename); // Create directories File path=new File(Other_People_header); if (!path.exists()) { path.mkdirs(); } if (!img.exists()) { Mythread mythread=new Mythread(filename,img); mythread.start(); if (!mythread.isAlive()) return true; } return true; } public static boolean getOwnImageByWeb(Context context,String filename) { myPicPath = “自己头像保存地址"; File img=new File(myPicPath+filename); Mythread mythread=new Mythread(filename,img); mythread.start(); if (!mythread.isAlive()) return true; return true; } public static Bitmap filesOtherToBitmap(Context context,String filename){ Other_People_header =“朋友头像保存地址";//头像保存的路径 Bitmap temp=null; if(filename!=null){ File imageFile = new File(Other_People_header+filename); if (imageFile.exists()) { // Load the image from file temp = BitmapFactory.decodeFile(Other_People_header+filename); } } return temp; } public static Bitmap filesOwnToBitmap(Context context,String filename){ myPicPath = "头像保存地址"; Bitmap temp=null; if(filename!=null){ File imageFile = new File(myPicPath+filename); if (imageFile.exists()) { // Load the image from file temp = BitmapFactory.decodeFile(myPicPath+filename); } } return temp; } static class Mythread extends Thread{ String filename; File img; public Mythread(String filename, File img) { this.filename = filename; this.img = img; } @Override public void run() { try { URL imageUrl = new URL("从服务器下载图片的位置" + filename); HttpURLConnection con = (HttpURLConnection) imageUrl.openConnection(); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestProperty("Charset", "UTF-8"); con.setRequestMethod("GET"); fileLegth=con.getContentLength();//得到文件的长度 InputStream in = imageUrl.openStream(); int process=0; OutputStream out = new BufferedOutputStream(new FileOutputStream(img)); for (int b; (b = in.read()) != -1;) { out.write(b); process=process+b;//获取到当前下载的进度 } out.close(); in.close(); } catch (MalformedURLException e) { img = null; } catch (IOException e) { img = null; } super.run(); } } }
从服务器下载图片
最新推荐文章于 2024-06-11 08:00:00 发布