java - 如何下载文件并将其另存为 JPEG

标签 java android android-download-manager

您好,我想在长按图片时下载图片。 我可以获取要下载的图像,但我不知道它下载到哪里。 它不在下载目录中。但是,如果我从通知中打开它,我可以看到图像。

下面是我的代码 fragment :

 @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;
                        }
                    });
        }
    }

最佳答案

这就是您的类(class)应有的样子。

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..
                }
            }
        }
    };


}

此答案基于我从以下资源中找到的代码: How to use Android DownloadManager?

https://stackoverflow.com/a/5879563/4127441

https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java

https://stackoverflow.com/a/19339672/4127441

关于java - 如何下载文件并将其另存为 JPEG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999726/

相关文章:

java - 在 Java 文件中出现 "The method isEmpty() is undefined for the type Optional"错误

java - 检测 Java 项目 Cruft

Android:是否有 .TranslationX() View 的更改监听器

Android 下载管理器 "Download Unsuccessful"

java - 下载管理器在网络断开和系统重启的情况下无法恢复下载

java - 为什么不可变类需要 final 关键字?

java - 如何设置JXTreeTable第一列的背景颜色

readFromParcel 方法中的 Android 类型不匹配

android - 如何将 GoogleMap fragment 包装成 LinearLayout?

java - 如何取消downloadManager启动的下载任务