0

下面是我用来从 url 获取图像并随后显示它的代码片段。

public Bitmap downloadFile(String fileUrl){
        URL myFileUrl =null;          
        try {
             myFileUrl= new URL(fileUrl);
        } catch (MalformedURLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
        }
        try {
             HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
             conn.setDoInput(true);
             conn.connect();
             InputStream is = conn.getInputStream();

            Bitmap bmImg = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
        }
       
        return bmImg;
   }

但我无法获取图像。我越来越java.io.FileNotFoundException: http://test.com/test.jpg

知道我的代码有什么问题吗?有没有其他方法可以从 url 获取图像?

4

2 回答 2

2

试试这个代码,它将 100% 工作。在异步类下面的活动调用中并传递您的 URL-

new GetImageFromUrl().execute(userImageUrl);

这是我的异步类-

 public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
    @Override protected Bitmap doInBackground(String... urls) {
        Bitmap map = null; for (String url : urls) { 
            map = downloadImage(url);
            } 
        return map;
        }
    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) { 
        imageProfile.setImageBitmap(result);
        } // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1; 
        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions); stream.close(); 
            }
        catch (IOException e1) {
            e1.printStackTrace(); 
            }
        return bitmap;
        } // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException { 
        InputStream stream = null; 
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
try { 
    HttpURLConnection httpConnection = (HttpURLConnection) connection; 
    httpConnection.setRequestMethod("GET"); 
    httpConnection.connect(); 
    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
    { stream = httpConnection.getInputStream(); 
    }
    }
catch (Exception ex) { 
    ex.printStackTrace();
    }
return stream;
}
    }

您还可以查看此链接,我从 gmail 获取图像并显示到 ImageView- http://www.androidhub4you.com/2013/09/google-account-integration-in-android.html

于 2013-10-16T05:12:46.667 回答
0

对于您的 Android 应用程序中的任何类型的下载,您应该使用 Async Task、Services 等。

您可以使用示例异步类模板:

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

private Context context;

public DownloadTask(Context context) {
    this.context = context;
}

@Override
protected void onPostExecute(String result) {
    mProgressDialog.dismiss();
    if (result != null)
        Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
        //HERE DISPLAY THE IMAGE TO THE DESIRED IMAGE VIEW
}

@Override
protected String doInBackground(String... sUrl) {
    // take CPU lock to prevent CPU from going off if the user 
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
         getClass().getName());
    wl.acquire();

    try {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report 
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                 return "Server returned HTTP " + connection.getResponseCode() 
                     + " " + connection.getResponseMessage();

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/myImage.jpg");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled())
                    return null;
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } 
            catch (IOException ignored) { }

            if (connection != null)
                connection.disconnect();
        }
    } finally {
        wl.release();
    }
    return null;
}
}

你可以简单地使用这个类来下载你的图像文件:

final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("http://www.myextralife.com/wp-content/uploads/2008/08/stack-overflow-grave-scene.jpg");

您将在 Method 中了解文件的下载状态onPoseExecute(...),您可以在其中将下载的图像简单地显示到您想要的 ImageView 中。
来源:使用 Android 下载文件,并在 ProgressDialog 中显示进度
我希望这会有所帮助。

于 2013-10-16T04:22:56.257 回答