我使用Picasso下载图像并在我的Android应用程序中显示,它工作正常。现在我想下载第一页中的所有图片,并在第二页中显示。问题是,图像将保存在哪里?我需要路径在那里下载图像。有什么方法可以访问路径或更改吗?
您可以使用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。我希望这能帮助你!:)