我在gridview中有一些图像。当我点击图像时,图像将在另一个活动中打开。在那个活动中我有一个保存按钮。单击保存按钮时,图像应下载并保存在SD卡中。现在我的问题是如何下载和保存图像。
这是我的代码
主要活动.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beaches);
GridView gridView = (GridView) findViewById(R.id.gridView1);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
Button home=(Button)findViewById(R.id.button1);
home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
Fullimageactivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beachfull);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.images[position]);
Button dwnld = (Button)findViewById(R.id.download);
dwnld.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
答案 0 :(得分:0)
以下代码是从网址
保存图像文件private String path;
private Bitmap bmImg;
void downloadFile(String fileUrl, String fileName) {
// here you can add folder in which you want the image to be stored
path = sdCard.getAbsolutePath() ;
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
if (bmImg != null) {
bmImg.recycle();
}
bmImg = BitmapFactory.decodeStream(is);
FileOutputStream out = new FileOutputStream(path + "/" + fileName + ".jpg");
bmImg.compress(Bitmap.CompressFormat.JPEG, 50, out);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
请记住,您还需要AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />