我使用 Picasso 下载图片并在我的 Android 应用中显示它,它可以正常工作。现在我想在第一页下载所有图像并在第二页中显示它们。问题是,图像将保存在哪里?我需要路径来下载图片。 有没有办法访问路径或更改呢?
答案 0 :(得分:0)
您可以使用它们的urrls将图像下载到内部存储上的所需路径,然后只需使用以下两种方法将它们加载到图像视图中:
public void downloadImagesToSdCard(String downloadUrl, String imageName)
//downloadURL is the url of your image and imageName is the name you choose for your image file on internal storage
{
try
{
URL url = new URL(downloadUrl);
/* making a directory in sdcard */
String sdCard= Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard,"Your Arbitrary Folder Name");
/* 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[2048];
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();
}
}`
使用上述方法后,您的图像从输入URL下载到设备的内部存储中的指定文件夹和图像名称(imageName)。然后,您应该将此路径中的图像加载到ImageView。您可以使用以下方法执行此操作:
public Bitmap loadToImageView(ImageView myImage, String sd_address) {
Bitmap myBitmap = null;
//File imgFile = new File("/sdcard/Your Arbitary Folder Name/matin.jpg");
File imgFile = new File(sd_address);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
return myBitmap;
}
因此,您的图像使用setImageBitmap方法从指定的sd_address加载到imageview。希望这对你有所帮助! :)