我正在尝试创建一个非常简单的图像下载应用程序。其中我想从此网址下载所有图片到SD卡:https://www.dropbox.com/sh/5be3kgehyg8uzh2/AAA-jYcy_21nLBwnZQ3TBFAea
此代码适用于在imageview中加载图片:
package com.example.imagedownloadsample;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_download);
final ImageView img = (ImageView) (findViewById(R.id.imageView1));
// File file = new File(Environment.getExternalStorageDirectory(),
// "Android/data/com.usd.pop");
Picasso.with(getApplicationContext())
.load("http://8020.photos.jpgmag.com/3456318_294166_528c960558_m.jpg")
.into(img);
}
}
但是当我尝试将此图像下载到SD卡时,我最终以不幸的应用程序停止错误:
package com.example.imagedownloadsample;
import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_download);
//final ImageView img = (ImageView) (findViewById(R.id.imageView1));
File file = new File(Environment.getExternalStorageDirectory(),
"Android/data/com.usd.pop");
Picasso.with(getApplicationContext())
.load("http://8020.photos.jpgmag.com/3456318_294166_528c960558_m.jpg")
.into((Target) file);
}
}
答案 0 :(得分:14)
我同意Ichigo Kurosaki的答案。以下是如何使用毕加索和毕加索目标的详细示例。
Picasso.with(ImageDetailActivity.this).load(
galleryObjects.get(mViewPager.getCurrentItem()).fullImagePath).into(target);
private Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(
Environment.getExternalStorageDirectory().getPath()
+ "/saved.jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,ostream);
ostream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
答案 1 :(得分:13)
您可以使用此AsyncTask
,这样就不会出现OnMainThread
异常。
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="Name"+".rar";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(fa, "File Downloaded", Toast.LENGTH_SHORT).show();
}
}
protected void onPostExecute(String result) {
}
}
将此课程复制到您的活动中。它不能是另一种方法。
你可以这样称呼它
new DownloadFile().execute(“yoururl”);
此外,将这些权限添加到您的清单。
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
答案 2 :(得分:1)
检查这些链接
Why use Android Picasso library to download images?
http://www.101apps.co.za/articles/gridview-tutorial-using-the-picasso-library.html
http://www.youtube.com/watch?v=tRTFwzUH_ek
http://square.github.io/picasso/
使用Picasso,您的代码只有一行
Picasso.with(context).load("your URL").into(your_imageView);
存储到外部SD卡
Android saving file to external storage
答案 3 :(得分:1)
使用毕加索在SD卡中保存图像,您可以执行以下操作
private Target mTarget = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Perform simple file operation to store this bitmap to your sd card
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
...
Picasso.with(this).load("url").into(mTarget);
这里&#34;目标&#34;是由毕加索提供的一个班级,它有一个非常简单的方法来理解...
希望这能满足您的需求
答案 4 :(得分:1)
Aquery是从url到SD卡下载图像的最快速最简单的方式。
try
{
String url=" "; \\Paste the Url.
aq.id(R.id.img).progress(R.id.progress).image(Url, true, true, 0, 0, new BitmapAjaxCallback()
{
@Override
public void callback(String url, ImageView iv,Bitmap bm, AjaxStatus status)
{
iv.setImageBitmap(bm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String EnString = Base64.encodeToString(b,Base64.DEFAULT);
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
File dir = new File(SDCardRoot.getAbsolutePath()+ "/Aquery" + "/Image");
//Download the Image In Sdcard
dir.mkdirs();
try
{
if (!SDCardRoot.equals(""))
{
String filename = "img"+ new Date().getTime() + ".png";
File file = new File(dir, filename);
if (file.createNewFile())
{
file.createNewFile();
}
if (EnString != null)
{
FileOutputStream fos = new FileOutputStream(file);
byte[] decodedString = android.util.Base64.decode(EnString,
android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();
}
}
}
} catch (Exception e) {
}
});
} catch (Exception e) {
}
如需更多参考,请点击此处http://androiddhina.blogspot.in/2015/03/androiddownload-image-using-aquery.html