Как я могу сохранить изображение с URL-адреса?

Я устанавливаю ImageView, используя setImageBitmap с внешним URL-адресом изображения. Я хотел бы сохранить изображение, чтобы его можно было использовать позже, даже если нет подключения к Интернету. Где и как я могу его сохранить?


person Amit    schedule 30.04.2012    source источник


Ответы (5)


Вы должны сохранить его на SD-карте или в данных вашего пакета, потому что во время выполнения у вас есть доступ только к ним. Для этого это хороший пример

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

Источник: Как передать изображение с его URL на SD-карту?

person Sarim Sidd    schedule 30.04.2012
comment
Этот код не будет компилироваться. Environment.getExternalStorageDirectory() не возвращает String. - person Jeff Axelrod; 11.08.2012
comment
Что такое разумный размер - person Ruchit Shah; 10.07.2015
comment
Точно! что такое разумный размер? - person Steve Kamau; 17.09.2016
comment
Я думаю, мы никогда не узнаем - person Denny; 18.10.2018
comment
@Denny aReasonableSize может быть 1024 и 2048. - person Sarim Sidd; 23.10.2018
comment
Это размер буфера (также известный как количество байтов для чтения/записи за раз). Чем больше размер буфера, тем больше данных будет прочитано/записано. - person Van; 24.05.2019

URL imageurl = new URL("http://mysite.com/me.jpg"); 
Bitmap bitmap = BitmapFactory.decodeStream(imageurl.openConnection().getInputStream()); 

Этот код поможет вам создать растровое изображение из URL-адреса изображения.

Этот вопрос отвечает на вторую часть.

person coderplus    schedule 30.04.2012

Если вы используете Kotlin и Glide в своем приложении, то это для вас:

Glide.with(this)
                .asBitmap()
                .load(imageURL)
                .into(object : SimpleTarget<Bitmap>(1920, 1080) {
                    override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
                        saveImage(bitmap)
                    }
                })

и это та самая функция

internal fun saveImage(image: Bitmap) {
    val savedImagePath: String

    val imageFileName = System.currentTimeMillis().toString() + ".jpg"
    val storageDir = File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).toString() + "/Folder Name")
    var success = true
    if (!storageDir.exists()) {
        success = storageDir.mkdirs()
    }
    if (success) {
        val imageFile = File(storageDir, imageFileName)
        savedImagePath = imageFile.absolutePath
        try {
            val fOut = FileOutputStream(imageFile)
            image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
            fOut.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        galleryAddPic(savedImagePath)
    }
}


private fun galleryAddPic(imagePath: String) {
    val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
    val f = File(imagePath)
    val contentUri = FileProvider.getUriForFile(applicationContext, packageName, f)
    mediaScanIntent.data = contentUri
    sendBroadcast(mediaScanIntent)
}

galleryAddPic() используется для просмотра изображения в телефонной галерее.

Примечание: теперь, если вы столкнулись с исключением файла uri, вам может помочь это.

person Kishan Solanki    schedule 09.08.2019

вы можете сохранить изображение на SD-карте, и вы можете использовать это изображение в будущем без интернета.

см. это руководство покажет как сохранить изображение и снова прочитать его.

Надеюсь, что это поможет вам.....!

person MAC    schedule 30.04.2012

Может быть, это поможет кому-то вроде меня однажды

 new SaveImage().execute(mViewPager.getCurrentItem());//calling function

private void saveImage(int currentItem) {
    String stringUrl = Site.BASE_URL + "socialengine/" + allImages.get(currentItem).getMaster();
    Utils.debugger(TAG, stringUrl);

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(stringUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        File sdCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();

        String fileName = stringUrl.substring(stringUrl.lastIndexOf('/') + 1, stringUrl.length());
        String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));

        File imgFile = new File(sdCardRoot, "IMG" + System.currentTimeMillis() / 100 + fileName);
        if (!sdCardRoot.exists()) {
            imgFile.createNewFile();
        }

        InputStream inputStream = urlConnection.getInputStream();
        int totalSize = urlConnection.getContentLength();
        FileOutputStream outPut = new FileOutputStream(imgFile);

        int downloadedSize = 0;
        byte[] buffer = new byte[2024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            outPut.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Utils.debugger("Progress:", "downloadedSize:" + Math.abs(downloadedSize*100/totalSize));
        }
        outPut.close();
        //if (downloadedSize == totalSize);
            //Toast.makeText(context, "Downloaded" + imgFile.getPath(), Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

 private class SaveImage extends AsyncTask<Integer, Void, String> {

    @Override
    protected String doInBackground(Integer... strings) {
        saveImage(strings[0]);
        return "saved";
    }

    @Override
    protected void onPostExecute(String s) {
        Toast.makeText(context, "" + s, Toast.LENGTH_SHORT).show();
    }
}
person Aklesh Singh    schedule 18.02.2017