如何从android中的URL下载图像

时间:2014-09-09 12:07:30

标签: java android

我在webview中显示图像,并在下载按钮上添加onclick侦听器。当用户点击下载按钮时,它会获得webview的地址(在这种情况下为www.realearnpak.com/test/1.jpg)。图像显示在webview中,但下载图像功能不起作用。

请提前帮助我。我尝试了从url下载图像的替代功能,但似乎不起作用。

public class MainActivity extends Activity {
    public void DownloadImageFromPath(String path){
        InputStream in =null;
        Bitmap bmp=null;

        int responseCode = -1;
        try{

             URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
             HttpURLConnection con = (HttpURLConnection)url.openConnection();
             con.setDoInput(true);
             con.connect();
             responseCode = con.getResponseCode();
             if(responseCode == HttpURLConnection.HTTP_OK)
             {
                 //download 
                 in = con.getInputStream();
                 bmp = BitmapFactory.decodeStream(in);
                 in.close();

             }

        }
        catch(Exception ex){
            Log.e("Exception",ex.toString());
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final WebView mWebView= (WebView) findViewById(R.id.webView1);
        mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onReceivedError(WebView view, int errorCode,
                        String description, String failingUrl) {
                    // Handle the error
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });

        mWebView.loadUrl("http://www.realearnpak.com/test/1.jpg");  


        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Reset...");       
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, final int which) {
        // here you can add functions
        }
        });



         final Button button = (Button) findViewById(R.id.button1);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click   
                 String webUrl = mWebView.getUrl();
                 //alertDialog.setMessage(webUrl);
                // alertDialog.show();  


                 DownloadImageFromPath(webUrl);

             }
         });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

3 个答案:

答案 0 :(得分:0)

以下是您可以根据需要调整的代码的一部分(但您需要将其放入asynctask等中):

// Defines a handle for the byte download stream
InputStream inputStream = null;
FileOutputStream outputStream = null;
HttpEntity entity = null;

// Downloads the image and catches IO errors
try {

    // Opens an HTTP connection to the image's URL
    final String imageURL = URLEncoder.encode("http://my-path/to-my/beautiful-picture.jp", "UTF-8").replaceAll("\\+", "%20");
    HttpGet httpRequest;
    try {
        httpRequest = new HttpGet(imageURL);
    } catch (Exception e) {
        Log.w(TAG, e);
        throw new InterruptedException();
    }

    HttpResponse response = new DefaultHttpClient().execute(httpRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + imageURL);
        throw new InterruptedException();
    }

    // Gets the input stream containing the image
    entity = response.getEntity();
    inputStream = new BufferedHttpEntity(entity).getContent();

    bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));

    if (bitmap == null) {
        Log.w(TAG, "Error while decoding bitmap from " + imageURL);
        throw new IllegalStateException();
    }

    outputStream = getContext().openFileOutput("Beautiful-picture.jpg", Context.MODE_PRIVATE);

    boolean ok = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

    if (!ok) {
        Log.w(TAG, "Error while compressing bitmap from " + imageURL);
        throw new IllegalStateException();
    }

    // If an IO error occurs, returns immediately
} catch (IOException e) {
    e.printStackTrace();
    return;

/*
 * If the input stream is still open, close it
 */
} finally {
    try {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != outputStream) {
            outputStream.close();
        }

        if (entity != null) {
            entity.consumeContent();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

对于FlushedInputStream,我让你自己看看:p

答案 1 :(得分:0)

有一个很棒的图书馆(实际上有一些)。我建议你使用其中一个,因为这是一个常见的活动(从网上下载图像),这不是自己做的事情。

我使用Picasso(这是常见的收藏),Universal Image Downloader是另一种选择。

答案 2 :(得分:0)