本文介绍了保存图像从URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要保存图像从URL的一个按钮在我的$ C $词有创建目标文件夹,但我已经尝试过各种codeS保存图片,但没有工作没有什么:
I want to save an image from a URL with a button in my code i have create the destination folder, but I have tried various codes to save a picture but do not work nothing :
public class B_X extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bx);
Button buttonSetWallpaper = (Button)findViewById(R.id.bSetWall);
buttonSetWallpaper.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
File folder = new File(Environment.getExternalStorageDirectory() + "/PerfectAss/");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (!success) {
} else {
}
Toast.makeText(getApplicationContext(), "The image has been saved", Toast.LENGTH_LONG).show();
URL url = new URL ("http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg");
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[1500];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
请帮我解决这个问题code。
Please help me fix this code.
推荐答案
使用这种方式的简单:它的保存文件SD卡/ dhaval_files /
。只需更换您的文件夹名称,并对在Android清单文件权限 WRITE_EXTERNAL_STORAGE
。
use this way its easy: its save file in "sdcard/dhaval_files/"
. just replace your folder name and give permission write_external_storage
in android manifest file.
public void file_download(String uRl) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/dhaval_files");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");
mgr.enqueue(request);
}
这篇关于保存图像从URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!