-1

我有以下代码可以很好地下载图像表单 url。我想通过单击按钮将加载在 imageview 中的图像保存到 sdcard。谁能帮助我如何将下载的图像保存到 SD 卡。

public class DownloadimageActivity extends Activity {
@Override  
public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
    }  
    public void downloadPicture(View view) {  
     final ProgressDialog dialog = ProgressDialog.show(this, "Snapshot",  
             "retriving image..");  
     dialog.show();  
     new Thread(new Runnable() {  
         @Override  
         public void run() {  
             try {  
                 final Bitmap downloadBitma = downloadBitmap("http://42.60.144.184:8081/snapshot.cgi?&user=admin&pwd=admin&resolution=8");  
                 final ImageView imageView = (ImageView) findViewById(R.id.imageView1);  
                 runOnUiThread(new Runnable() {  
                     @Override  
                     public void run() {  
                         imageView.setImageBitmap(downloadBitma);  

                     }  
                 });  

             } catch (IOException e) {  
                 e.printStackTrace();  
             } finally {  
                 dialog.dismiss();  
             }  
         }  
     }).start();  

 }  

 private Bitmap downloadBitmap(String url) throws IOException {  
     HttpUriRequest request = new HttpGet(url.toString());  
     HttpClient httpClient = new DefaultHttpClient();  
     HttpResponse response = httpClient.execute(request);  

     StatusLine statusLine = response.getStatusLine();  
     int statusCode = statusLine.getStatusCode();  
     if (statusCode == 200) {  
         HttpEntity entity = response.getEntity();  
         byte[] bytes = EntityUtils.toByteArray(entity);  

         Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,  
                 bytes.length);  

         return bitmap;  
     } else {  
         throw new IOException("Retrive failed, HTTP response code "  
                 + statusCode + " - " + statusLine.getReasonPhrase());  
     }

 }
 }

我尝试使用以下代码,但它不起作用。

     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     downloadBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
     //you can create a new file name "test.jpg" in sdcard folder.
     File f = new File(Environment.getExternalStorageDirectory()
                             + File.separator + "test.jpg");
     f.createNewFile();
     //write the bytes in file
     FileOutputStream fo = new FileOutputStream(f);
     fo.write(bytes.toByteArray());
4

1 回答 1

1
final Bitmap downloadBitma = downloadBitmap(...);

您的位图名称末尾缺少“p”,因此这不起作用...

downloadBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

哦,不要给变量和方法同名——我什至不知道这在 Java 中是否合法。

于 2012-05-08T00:25:59.280 回答