0

我需要从 URL http://blogs.fco.gov.uk/peterbeckingham/files/2012/08/goa-beach.jpg获取图像, 这非常容易访问。这是我的一段代码,

public class MainActivity extends Activity {
ImageView templateImage;
Bitmap bm;
String templateImageURL;
byte[] binaryURL=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        templateImage=(ImageView)findViewById(R.id.templateImage);
        templateImageURL="http://blogs.fco.gov.uk/peterbeckingham/files/2012/08/goa-beach.jpg";
        DownloadImageTask dwnloadtask=new DownloadImageTask();
        dwnloadtask.execute();
    }

private class DownloadImageTask extends AsyncTask<Void, Void, Void> {
         Drawable image;
                protected Void doInBackground(Void... urls) {
              image = ImageOperations(getApplicationContext(), templateImageURL, "image.jpg");
            return null;
        }

        protected void onPostExecute(Void result) {
             templateImage.setImageDrawable(image);
        }
        private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
            try {
                InputStream is = (InputStream) fetch(url);
                Drawable d = Drawable.createFromStream(is, "src");
                return d;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

        }
         public Object fetch(String address) throws MalformedURLException,IOException {
                URL url = new URL(address);
                Object content = url.getContent();
                return content;
            }
    }

这是XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/templateImage" />

</RelativeLayout>

这是清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imageurldemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.imageurldemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我得到的异常,尽管文件可用

10-04 11:00:10.394: W/System.err(17887): java.io.FileNotFoundException: http://blogs.fco.gov.uk/peterbeckingham/files/2012/08/goa-beach.jpg
10-04 11:00:10.394: W/System.err(17887):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
10-04 11:00:10.394: W/System.err(17887):    at java.net.URLConnection$DefaultContentHandler.getContent(URLConnection.java:1018)
10-04 11:00:10.394: W/System.err(17887):    at java.net.URLConnection.getContent(URLConnection.java:199)
10-04 11:00:10.399: W/System.err(17887):    at java.net.URL.getContent(URL.java:447)
10-04 11:00:10.399: W/System.err(17887):    at com.example.imageurldemo.MainActivity$DownloadImageTask.fetch(MainActivity.java:105)
10-04 11:00:10.399: W/System.err(17887):    at com.example.imageurldemo.MainActivity$DownloadImageTask.ImageOperations(MainActivity.java:91)
10-04 11:00:10.399: W/System.err(17887):    at com.example.imageurldemo.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:111)
10-04 11:00:10.399: W/System.err(17887):    at com.example.imageurldemo.MainActivity$DownloadImageTask.doInBackground(MainActivity.java:1)
10-04 11:00:10.399: W/System.err(17887):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-04 11:00:10.399: W/System.err(17887):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-04 11:00:10.399: W/System.err(17887):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-04 11:00:10.399: W/System.err(17887):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-04 11:00:10.399: W/System.err(17887):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-04 11:00:10.399: W/System.err(17887):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-04 11:00:10.399: W/System.err(17887):    at java.lang.Thread.run(Thread.java:856)
4

2 回答 2

0

你为什么要做这种漫长的过程?当 Android 为我们提供了很好的工作时。请参阅下面我的答案,它将非常有用并且可以使用。

我可以推荐一种像魅力一样工作的不同方式:Android Query。

您可以从这里下载该 jar 文件:http ://code.google.com/p/android-query/downloads/list

AQuery androidAQuery=new AQuery(this);
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

它非常快速和准确,使用它您可以在加载时找到更多功能,例如动画;如果需要,获取位图;等等

于 2013-10-04T05:35:38.243 回答
0

试试下面的代码从 url 下载图像。

  // DownloadImage AsyncTask
    private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
     @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Downloading Image.... ");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }
     @Override
    protected Bitmap doInBackground(String... URL) {
         String imageURL = URL[0];
         Bitmap bitmap = null;
        try {
            // Download Image from URL
            InputStream input = new java.net.URL(imageURL).openStream();
            // Decode Bitmap
            bitmap = BitmapFactory.decodeStream(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
     @Override
    protected void onPostExecute(Bitmap result) {
        // Set the bitmap into ImageView
        image.setImageBitmap(result);
        // Close progressdialog
        mProgressDialog.dismiss();
    }
      }
  } 

使用上面的代码如下:

      templateImageURL="http://blogs.fco.gov.uk/peterbeckingham/files/2012/08/goa-beach.jpg";
        // Execute DownloadImage AsyncTask
        new DownloadImage().execute(templateImageURL);

此外,为了从 url 加载图像,我们首先需要将图像存储在一个临时位置,一旦下载它就应该添加到ImageView. 要创建临时文件,我们需要访问设备外部存储。AndroidManifest.xml向文件添加所需的权限。不需要ACCESS_NETWORK_STATE许可。

   To access external storage required permission is – WRITE_EXTERNAL_STORAGE
于 2013-10-04T05:38:22.910 回答