Java 如何下载文件并将其另存为JPEG
嗨,我想在长按图像时下载图像。 我可以下载图像,但我不知道它下载到哪里。 它不在下载目录中。但是,如果我从通知中打开它,我可以看到图像 下面是我的代码片段:Java 如何下载文件并将其另存为JPEG,java,android,android-download-manager,Java,Android,Android Download Manager,嗨,我想在长按图像时下载图像。 我可以下载图像,但我不知道它下载到哪里。 它不在下载目录中。但是,如果我从通知中打开它,我可以看到图像 下面是我的代码片段: @Override public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){ super.onCreateContextMenu(contextM
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){
super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
contextMenu.setHeaderTitle("Download Image");
contextMenu.add(0, 1, 0, "Save - Download Image")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
String DownloadImageURL = webViewHitTestResult.getExtra();
if(URLUtil.isValidUrl(DownloadImageURL)){
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(MainActivity.this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show();
}
return false;
}
});
}
}
这就是你们班的样子
public class YourActivity extends Activity {
private WebView webView; // make sure to init your webview
private DownloadManager downloadManager;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// your any other onCreate() code...
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
registerReceiver(onDownloadComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
if (isHitResultAnImage(webViewHitTestResult)) {
contextMenu.setHeaderTitle("Download Image");
contextMenu.add(0, 1, 0, "Save - Download Image")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return handleMenuItemClick(menuItem, webViewHitTestResult.getExtra());
}
});
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
}
private boolean isHitResultAnImage(WebView.HitTestResult hitTestResult) {
return hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE;
}
private boolean handleMenuItemClick(MenuItem menuItem, String imageDownloadUrl) {
if(URLUtil.isValidUrl(imageDownloadUrl)){
downloadImage(imageDownloadUrl);
Toast.makeText(this,"Image Downloaded Successfully.",Toast.LENGTH_LONG).show();
return false;
}
Toast.makeText(this,"Sorry.. Something Went Wrong.",Toast.LENGTH_LONG).show();
return false;
}
private void downloadImage(String imageUrl) {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
}
public String getFilePathFromUri(Uri uri) {
String filePath = null;
if ("content".equals(uri.getScheme())) {
String[] filePathColumn = { MediaStore.MediaColumns.DATA };
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(uri, filePathColumn, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
} else if ("file".equals(uri.getScheme())) {
filePath = new File(uri.getPath()).getAbsolutePath();
}
return filePath;
}
private void saveAsJpeg(Bitmap bitmapImage) {
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory,"imageName.jpg");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
File file = new File(getFilePathFromUri(Uri.parse(uriString)));
try {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
saveAsJpeg(bitmap);
} catch (FileNotFoundException e) {
// cant save
}
} else {
// downloadFailed, show toast or something..
}
}
}
};
}
这个答案基于我从以下资源中找到的代码:
你能看一下这个问题吗:我看了,但这对我没什么帮助:/
Toast.makeText(MainActivity.this,“图像下载成功”,Toast.LENGTH\u LONG).show()代码>。你不能把烤面包放在那里。您刚刚要求下载管理器下载一个文件。也许下载还没有开始。下载失败的原因有很多。Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_D
OWNLOADS);`。那句话毫无用处。当然,你应该告诉下载管理器这个路径。我试过你的代码示例。它的工作原理和以前一样。如何将.jpg中的文件写入目录?因为现在,它只是下载而已。我更新并添加了将文件转换为位图的代码,以及获取位图并将其保存为jpeg文件的方法。我发现如何在谷歌搜索10分钟内将文件保存为jpeg格式。试着把你的问题分解成更小的问题单元,并单独解决它们,这种系统化的方法会把你带到正确的位置。还有一个技巧,试着编写可读性更强的代码,这将帮助你和其他人阅读你的代码。它的工作原理和以前一样。而且我也找不到您创建的目录:/是否可以使用标准下载目录?或者图片目录?我创建了一个聊天室,并对您的问题进行了升级,您应该有足够的分数可以进入聊天室,我将向您发送聊天邀请,我们可以在那里轻松讨论。非常好,非常感谢:)在您发送邀请后,我可以在哪里看到您的邀请?