Android - 将 URL 中的图像保存到 SD 卡上

发布于 2024-10-15 16:24:07 字数 585 浏览 4 评论 0原文

我想将 URL 中的图像保存到 SD 卡(以供将来使用),然后从 SD 卡加载该图像以将其用作 Google 地图的可绘制叠加层。

以下是该函数的保存部分:

//SAVE TO FILE

String filepath = Environment.getExternalStorageDirectory().getAbsolutePath(); 
String extraPath = "/Map-"+RowNumber+"-"+ColNumber+".png";
filepath += extraPath;

FileOutputStream fos = null;
fos = new FileOutputStream(filepath); 

bmImg.compress(CompressFormat.PNG, 75, fos);

//LOAD IMAGE FROM FILE
Drawable d = Drawable.createFromPath(filepath);
return d;

图像成功保存到 SD 卡,但在到达 createFromPath() 行时失败。我不明白为什么它会保存到该目的地但不能从它加载......

I want to save an image from a URL to the SD card (for future use) and then load that image from the SD card to use it as a drawable overlay for Google maps.

Here is the save section of the function:

//SAVE TO FILE

String filepath = Environment.getExternalStorageDirectory().getAbsolutePath(); 
String extraPath = "/Map-"+RowNumber+"-"+ColNumber+".png";
filepath += extraPath;

FileOutputStream fos = null;
fos = new FileOutputStream(filepath); 

bmImg.compress(CompressFormat.PNG, 75, fos);

//LOAD IMAGE FROM FILE
Drawable d = Drawable.createFromPath(filepath);
return d;

The image is saved to the sd card succuessfully but fails when getting to the createFromPath() line. I don't understand why it would save ok to that destination but not load from it....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

老旧海报 2024-10-22 16:24:07

试试这个代码。它有效...

try
{   
  URL url = new URL("Enter the URL to be downloaded");
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);                   
  urlConnection.connect();                  
  File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
  String filename="downloadedFile.png";   
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot,filename);
  if(file.createNewFile())
  {
    file.createNewFile();
  }                 
  FileOutputStream fileOutput = new FileOutputStream(file);
  InputStream inputStream = urlConnection.getInputStream();
  int totalSize = urlConnection.getContentLength();
  int downloadedSize = 0;   
  byte[] buffer = new byte[1024];
  int bufferLength = 0;
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
  {                 
    fileOutput.write(buffer, 0, bufferLength);                  
    downloadedSize += bufferLength;                 
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }             
  fileOutput.close();
  if(downloadedSize==totalSize) filepath=file.getPath();    
} 
catch (MalformedURLException e) 
{
  e.printStackTrace();
} 
catch (IOException e)
{
  filepath=null;
  e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;

Try this code.It works...

try
{   
  URL url = new URL("Enter the URL to be downloaded");
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);                   
  urlConnection.connect();                  
  File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
  String filename="downloadedFile.png";   
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot,filename);
  if(file.createNewFile())
  {
    file.createNewFile();
  }                 
  FileOutputStream fileOutput = new FileOutputStream(file);
  InputStream inputStream = urlConnection.getInputStream();
  int totalSize = urlConnection.getContentLength();
  int downloadedSize = 0;   
  byte[] buffer = new byte[1024];
  int bufferLength = 0;
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
  {                 
    fileOutput.write(buffer, 0, bufferLength);                  
    downloadedSize += bufferLength;                 
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }             
  fileOutput.close();
  if(downloadedSize==totalSize) filepath=file.getPath();    
} 
catch (MalformedURLException e) 
{
  e.printStackTrace();
} 
catch (IOException e)
{
  filepath=null;
  e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
雪若未夕 2024-10-22 16:24:07

尝试使用此代码将图像从 URL 保存到 SDCard。

URL url = new URL ("file://some/path/anImage.png"); 
InputStream input = url.openStream(); 
try {     
    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(); 
}

如果要在 SD 卡上创建子目录,请使用:

File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper");
storagePath.mkdirs();

创建子目录“/sdcard/Wallpaper/”。

希望它能帮助你。

享受。 :)

Try this code to save the Image from the URL to SDCard.

URL url = new URL ("file://some/path/anImage.png"); 
InputStream input = url.openStream(); 
try {     
    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(); 
}

If you want to create a sub directory on the SD card use:

File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper");
storagePath.mkdirs();

To create a the sub directory "/sdcard/Wallpaper/".

Hope it will help you.

Enjoy. :)

小草泠泠 2024-10-22 16:24:07

我也遇到了同样的问题并解决了我的问题。尝试

private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
        {
            @Override
            protected Bitmap doInBackground(String... arg0) 
            {           
                downloadImagesToSdCard("","");
                return null;
            }

               private void downloadImagesToSdCard(String downloadUrl,String imageName)
                {
                    try
                    {
                        URL url = new URL(img_URL); 
                        /* making a directory in sdcard */
                        String sdCard=Environment.getExternalStorageDirectory().toString();     
                        File myDir = new File(sdCard,"test.jpg");

                        /*  if specified not exist create new */
                        if(!myDir.exists())
                        {
                            myDir.mkdir();
                            Log.v("", "inside mkdir");
                        }

                        /* checks the file and if it already exist delete */
                        String fname = imageName;
                        File file = new File (myDir, fname);
                        if (file.exists ()) 
                            file.delete (); 

                             /* Open a connection */
                        URLConnection ucon = url.openConnection();
                        InputStream inputStream = null;
                        HttpURLConnection httpConn = (HttpURLConnection)ucon;
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();

                          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                          {
                           inputStream = httpConn.getInputStream();
                          }

                            FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                        int downloadedSize = 0;   
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                        {                 
                          fos.write(buffer, 0, bufferLength);                  
                          downloadedSize += bufferLength;                 
                          Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                        }   

                            fos.close();
                            Log.d("test", "Image Saved in sdcard..");                      
                    }
                    catch(IOException io)
                    {                  
                         io.printStackTrace();
                    }
                    catch(Exception e)
                    {                     
                        e.printStackTrace();
                    }
                }           
        } 

在 AsyncTask 中声明您的网络操作,因为它将作为后台任务加载。不要在主线程上加载网络操作。
之后,在按钮单击或在内容视图中调用此类

 new ImageDownloadAndSave().execute("");

,不要忘记添加网络权限:

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

希望这可以帮助某人:-)

I also faced the same issue and resolved mine with this. Try this

private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
        {
            @Override
            protected Bitmap doInBackground(String... arg0) 
            {           
                downloadImagesToSdCard("","");
                return null;
            }

               private void downloadImagesToSdCard(String downloadUrl,String imageName)
                {
                    try
                    {
                        URL url = new URL(img_URL); 
                        /* making a directory in sdcard */
                        String sdCard=Environment.getExternalStorageDirectory().toString();     
                        File myDir = new File(sdCard,"test.jpg");

                        /*  if specified not exist create new */
                        if(!myDir.exists())
                        {
                            myDir.mkdir();
                            Log.v("", "inside mkdir");
                        }

                        /* checks the file and if it already exist delete */
                        String fname = imageName;
                        File file = new File (myDir, fname);
                        if (file.exists ()) 
                            file.delete (); 

                             /* Open a connection */
                        URLConnection ucon = url.openConnection();
                        InputStream inputStream = null;
                        HttpURLConnection httpConn = (HttpURLConnection)ucon;
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();

                          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                          {
                           inputStream = httpConn.getInputStream();
                          }

                            FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                        int downloadedSize = 0;   
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                        {                 
                          fos.write(buffer, 0, bufferLength);                  
                          downloadedSize += bufferLength;                 
                          Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                        }   

                            fos.close();
                            Log.d("test", "Image Saved in sdcard..");                      
                    }
                    catch(IOException io)
                    {                  
                         io.printStackTrace();
                    }
                    catch(Exception e)
                    {                     
                        e.printStackTrace();
                    }
                }           
        } 

Declare your network operations in AsyncTask as it will load it as a background task. Don't load network operation on main thread.
After this either in button click or in content view call this class like

 new ImageDownloadAndSave().execute("");

And don't forget to add the nework permission as:

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

Hope this may help someone :-)

帅哥哥的热头脑 2024-10-22 16:24:07

我相信它失败了,因为您正在将位图的压缩版本写入输出流,该输出流应该使用 BitmapFactory.decodeStream() 加载。有一个 快速查看这方面的文档。

如果您需要 DrawabledecodeStream() 返回 Bitmap),只需调用 Drawable d = new BitmapDrawable(bitmap).

I believe it's failing because you're writing a compressed version of the bitmap to the output stream, which should be loaded with BitmapFactory.decodeStream(). Have a quick look at the documentation on this.

If you need a Drawable (decodeStream() returns a Bitmap), simply call Drawable d = new BitmapDrawable(bitmap).

药祭#氼 2024-10-22 16:24:07

尝试这个代码..它工作正常

public static Bitmap loadImageFromUrl(String url) {
            URL m;
            InputStream i = null;
            BufferedInputStream bis = null;
            ByteArrayOutputStream out =null;
            try {
                m = new URL(url);
                i = (InputStream) m.getContent();
                bis = new BufferedInputStream(i,1024 * 8);
                out = new ByteArrayOutputStream();
                int len=0;
                byte[] buffer = new byte[1024];
                while((len = bis.read(buffer)) != -1){
                    out.write(buffer, 0, len);
                }
                out.close();
                bis.close();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = out.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            //Drawable d = Drawable.createFromStream(i, "src");
            return bitmap;
        }

并将位图保存到目录中

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.jpg")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();

,并且不要忘记向清单添加权限

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

Try this code..It works fine

public static Bitmap loadImageFromUrl(String url) {
            URL m;
            InputStream i = null;
            BufferedInputStream bis = null;
            ByteArrayOutputStream out =null;
            try {
                m = new URL(url);
                i = (InputStream) m.getContent();
                bis = new BufferedInputStream(i,1024 * 8);
                out = new ByteArrayOutputStream();
                int len=0;
                byte[] buffer = new byte[1024];
                while((len = bis.read(buffer)) != -1){
                    out.write(buffer, 0, len);
                }
                out.close();
                bis.close();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = out.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            //Drawable d = Drawable.createFromStream(i, "src");
            return bitmap;
        }

and save the bitmap into directory

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.jpg")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();

and do not forget to add permission to manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
裸钻 2024-10-22 16:24:07

试试这个...完成任务的简单方法。

Picasso.with(getActivity())
                .load(url)
                .into(new Target() {
                          @Override
                          public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                              try {
                                  String root = Environment.getExternalStorageDirectory().toString();
                                  File myDir = new File(root + "/yourDirectory");

                                  if (!myDir.exists()) {
                                      myDir.mkdirs();
                                  }

                                  String name = new Date().toString() + ".jpg";
                                  myDir = new File(myDir, name);
                                  FileOutputStream out = new FileOutputStream(myDir);
                                  bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

                                  out.flush();
                                  out.close();
                              } catch(Exception e){
                                  // some action
                              }
                          }

                          @Override
                          public void onBitmapFailed(Drawable errorDrawable) {
                          }

                          @Override
                          public void onPrepareLoad(Drawable placeHolderDrawable) {
                          }
                      }
                );

Try this... An easy way to the task done.

Picasso.with(getActivity())
                .load(url)
                .into(new Target() {
                          @Override
                          public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                              try {
                                  String root = Environment.getExternalStorageDirectory().toString();
                                  File myDir = new File(root + "/yourDirectory");

                                  if (!myDir.exists()) {
                                      myDir.mkdirs();
                                  }

                                  String name = new Date().toString() + ".jpg";
                                  myDir = new File(myDir, name);
                                  FileOutputStream out = new FileOutputStream(myDir);
                                  bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

                                  out.flush();
                                  out.close();
                              } catch(Exception e){
                                  // some action
                              }
                          }

                          @Override
                          public void onBitmapFailed(Drawable errorDrawable) {
                          }

                          @Override
                          public void onPrepareLoad(Drawable placeHolderDrawable) {
                          }
                      }
                );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文