如何从URL获取图像并将其存储在Bitmap变量中

时间:2016-07-01 10:55:45

标签: java android

我是Android新手。我想从url获取图像并设置为Bitmap变量。我尝试了很多代码,但我没有得到。

这是我的代码:

String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;

ImageDownloaderTask.java

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

Bitmap bImage;

@Override
public Bitmap doInBackground(String... params) {
    return downloadBitmap(params[0]);
}

private Bitmap downloadBitmap(String src) {
   HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(src);
        urlConnection = (HttpURLConnection) url.openConnection();

        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
    } catch (Exception e) {
        Log.d("URLCONNECTIONERROR", e.toString());
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        Log.w("ImageDownloader", "Error downloading image from " + src);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();

        }
    }
    return null;
}

protected void onPostExecute(Bitmap result) {
      bImage = result;
}
}

提前致谢...

7 个答案:

答案 0 :(得分:1)

以下是您可以使用的代码

new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");



// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog

    }

    @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) {
        // Do whatever you want to do with the bitmap

    }
}

答案 1 :(得分:0)

尝试以下代码:

URL url = new URL("https://www.google.com/intl/en_ALL/images/logo.gif");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());

并在清单中添加此权限:

<uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:0)

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

要在sdcard中保存位图,请使用以下代码

商店图片

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

获取图像存储路径

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

答案 3 :(得分:0)

从您的代码中

ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;

你得到一张空图像,因为你的ImageDownloaderTask尚未在图像中完成下载。

尝试更新onPosExecute上的图片:

protected void onPostExecute(Bitmap result) {
      bImage = result;
      // Update image here.
}

答案 4 :(得分:0)

Bitmap bmp;
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {



    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {

      bmp=result
    }}

答案 5 :(得分:0)

试试这个,

URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or 
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
    byte[] buffer = new byte[aReasonableSize];
    int bytesRead = 0;
    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
        output.write(buffer, 0, bytesRead);
    }
} finally {
    output.close();
}
} finally {
input.close();
}

答案 6 :(得分:0)

在我看来,最好为此创建一个界面:

public interface ImageDownloaderResponse {
    void downloadFinished(Bitmap bm);
}

在你的ImageDownloaderTask中:

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

    Bitmap bImage;
    public ImageDownloaderResponse delegate = null;

    @Override
    public Bitmap doInBackground(String... params) {
        return downloadBitmap(params[0]);
    }

    private Bitmap downloadBitmap(String src) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(src);
            urlConnection = (HttpURLConnection) url.openConnection();

            int statusCode = urlConnection.getResponseCode();


            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            Log.d("URLCONNECTIONERROR", e.toString());
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            Log.w("ImageDownloader", "Error downloading image from " + src);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();

            }
        }
        return null;
    }

    protected void onPostExecute(Bitmap result) {
        delegate.downloadFinished(result);
    }
}

然后让你的activity / fragment实现如下界面:

public class MainActivity extends AppCompatActivity implements ImageDownloaderResponse {

并使用您的Downloadtask:

String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(url);

并将其添加到您的活动/片段中:

@Override
public void downloadFinished(Bitmap bm) {
    Bitmap bitmap = bm;
}