English 中文(简体)
我怎么能从ur中挽救形象?
原标题:How can I save an image from a url?

I m setting an ImageView using setImageBitmap with an external image url. I would like to save the image so it can be used later on even if there is no internet connection. Where and how can I save it?

最佳回答

你们必须用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卡转至SD卡?

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

该法典将帮助你从图像陶里绘制地图。

question 对第二部分的答复。

If you are using Kotlin and Glide in your app then this is for you:

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() is used to see the image in a phone gallery.

能够帮助你们。

你们可以挽救card片中的图像,今后不使用互联网就能够使用这种形象。

,见本指南将显示如何储存图像,并再次阅读。

希望这将有助于你们......!

愿帮助像我这样的人一天。

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




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签