我是根据一个URL从网上解析到的图片,代码如下:
//创建一个url对象
URL url=new URL(showHeadimg);
//打开URL对应的资源输入流
InputStream is= url.openStream();
//从InputStream流中解析出图片
Bitmap bitmap = BitmapFactory.decodeStream(is);
现在想把这个bitmap转成一个File类型提交到后台,请问要怎么做?
请各位帮帮忙了!
http://zhidao.baidu.com/question/375289037
http://zhidao.baidu.com/question/1303109324555970699
楼主不想缓存本地?流都拿到了为啥不直接用流?再说了File本身定义就是磁盘文件的抽象与封装,要传输的话,直接用流更方便啊
public static String saveBitMapToFile(Context context, String fileName, Bitmap bitmap, boolean isCover) {
if(null == context || null == bitmap) {
return null;
}
if(TextUtils.isEmpty(fileName)) {
return null;
}
FileOutputStream fOut = null;
try {
File file = null;
String fileDstPath = "";
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
// 保存到sd卡
fileDstPath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "MyFile" + File.separator + fileName;
File homeDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "MyFile" + File.separator);
if (!homeDir.exists()) {
homeDir.mkdirs();
}
} else {
// 保存到file目录
fileDstPath = context.getFilesDir().getAbsolutePath()
+ File.separator + "MyFile" + File.separator + fileName;
File homeDir = new File(context.getFilesDir().getAbsolutePath()
+ File.separator + "MyFile" + File.separator);
if (!homeDir.exists()) {
homeDir.mkdir();
}
}
file = new File(fileDstPath);
if (!file.exists() || isCover) {
// 简单起见,先删除老文件,不管它是否存在。
file.delete();
fOut = new FileOutputStream(file);
if (fileName.endsWith(".jpg")) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
} else {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
}
fOut.flush();
bitmap.recycle();
}
Log.i("FileSave", "saveDrawableToFile " + fileName
+ " success, save path is " + fileDstPath);
return fileDstPath;
} catch (Exception e) {
Log.e("FileSave", "saveDrawableToFile: " + fileName + " , error", e);
return null;
} finally {
if(null != fOut) {
try {
fOut.close();
} catch (Exception e) {
Log.e("FileSave", "saveDrawableToFile, close error", e);
}
}
}
}
把inputstream写到outputstream中再构造post报文上传到服务器
out.write(header);
updateProgress(header.length);
FileInputStream inputStream = new FileInputStream(file);
final byte[] tmp = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(tmp)) != -1) {
out.write(tmp, 0, bytesRead);
updateProgress(bytesRead);
}
out.write(CR_LF);
updateProgress(CR_LF.length);
out.flush();