保存来自网址的图像[重复]

2024-03-17

我想用我的代码中的按钮保存来自 URL 的图像,我已经创建了目标文件夹,但我尝试了各种代码来保存图片,但没有任何作用:

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();
                              }

请帮我修复此代码。


您是否在清单文件中包含了权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

并尝试这个代码

或者然后尝试这个代码,它会起作用

URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();

try {
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory()
    File storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (storagePath + "/myImage.png");

    try {
        byte[] buffer = new byte[aReasonableSize];
        int bytesRead = 0;

        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
            output.write(buffer, 0, bytesRead);
        }
    } finally { output.close(); }
} finally { input.close(); }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

保存来自网址的图像[重复] 的相关文章

随机推荐