从网络上获取图片并保存在sdCard上

 package com.aib.soft;

 import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log; public class Util { /*
* 根据url从网络中获取一张图片
*
*/
public static Bitmap getHttpBitmap(String url) { URL myFileURL; Bitmap bitmap = null; try { myFileURL = new URL(url); // 获得连接 HttpURLConnection conn = (HttpURLConnection) myFileURL
.openConnection(); // 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制 conn.setConnectTimeout(60000); // 连接设置获得数据流 conn.setDoInput(true); // 不使用缓存 conn.setUseCaches(false); // 这句可有可无,没有影响 // conn.connect(); // 得到数据流 InputStream is = conn.getInputStream(); // 解析得到图片 bitmap = BitmapFactory.decodeStream(is); // 关闭数据流 is.close(); } catch (Exception e) { e.printStackTrace(); } return bitmap; } /**
* Save Bitmap to a file.保存图片到SD卡。
*
* @param bitmap
* @param file
* @return error message if the saving is failed. null if the saving is
* successful.
* @throws IOException
*/
public static void saveBitmapToFile(Bitmap bitmap, String _file)throws IOException {
BufferedOutputStream os = null;
try {
// Log.e("aib", "保存图片开始");
File file = new File(_file);
// String _filePath_file.replace(File.separatorChar +
// file.getName(), "");
int end = _file.lastIndexOf(File.separator);
String _filePath = _file.substring(0, end);
File filePath = new File(_filePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
// Log.e("aib", "已创建目录");
file.createNewFile();
// Log.e("aib", "createNewFile()");
os = new BufferedOutputStream(new FileOutputStream(file));
// Log.e("aib", "new BufferedOutputStream");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
// Log.e("aib", "保存图片结束");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
Log.e("aib", e.getMessage(), e);
}
}
}
}
}
上一篇:SSH框架简化


下一篇:Xubuntu VNC Xfce4