簡體   English   中英

如何從url獲取圖像並將其存儲在Bitmap變量中

[英]How to get Image from url and store it in Bitmap variable

我是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;
}
}

提前致謝...

這是您可以使用的代碼

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

    }
}

試試下面的代碼:

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" />
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;
} 

根據您的代碼,

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

嘗試這個,

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

我認為最好為此創建一個接口:

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

然后讓您的活動/片段實現這樣的接口:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM