我在项目中遇到了这个问题,我需要将图像作为文件传递图像来自URL(示例:图像URL this url需要转换为文件而不下载图像) ,意味着图像URL需要转换文件然后传递给服务器。分析但我没有得到任何答案,
{
"templateName": "e. Before-After(1).png",
"templateId": "",
"templateUrl": "https://cnet4.cbsistatic.com/img/QJcTT2ab-sYWwOGrxJc0MXSt3UI=/2011/10/27/a66dfbb7-fdc7-11e2-8c7c-d4ae52e62bcc/android-wallpaper5_2560x1600_1.jpg"
}
从此回复" templateUrl"需要转换文件
答案 0 :(得分:0)
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
File file = CommonUtils.getDownloadFile(placeHolder);
if (file == null)
return;
try {
FileOutputStream out = new FileOutputStream(file);
result.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
// here you can get file in "file" variable.
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Function for create a file where file download.
public static File getDownloadFile(String placeHolder) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/proManager");
if (!myDir.exists()) {
if (!myDir.mkdirs()) {
return null;
}
}
String fname = FILE_NAME_PRE_TEXT + placeHolder + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
return file;
}
如何使用此课程
ImageDownloaderTask imageDownloaderTask = new ImageDownloaderTask();
imageDownloaderTask.execute(url);