ImageView มีวิธีที่จะเอารูปภายนอกโปรแกรมมาใช้ โดยผ่าน Method setImageURI(String) แต่นั้นสิ มันสามารถใช้ได้เฉพาะรูปที่อยู่ใน SD Card หรืออยู่ในเครื่องได้เท่านั้น

แต่ถ้าหากจะเอารูปภายนอก เช่นอยากจะเอารูปถ่ายดาวเที่ยมล่าสุดจากเว็บต่างๆ มาแสดงในโปรแกรม โปรแกรมนั้นจำเป็นต้อง Connect Internet เพื่อดึงรูปภาพมาแสดง แต่จะแสดงยังไงได้หล่ะในเมื่อ setImageURI ใช้ได้เฉพาะรูปภาพที่อยู่ภายในเครื่องหรือ SD เท่านั้น

บทความนี้ผมก็จะเสนอวิธีการนำรูปภาพดังกล่าวมาใส่โปรแกรมของเราซึ่งมีขั้นตอนดังนี้

ส่วนแรก ผมตั้งชื่อว่า fetchImage จะใช้ในการเป็น Method ที่ช่วยดึงข้อมูลรูปภาพจาก URL ที่เรียก โดยจะส่งกลับเป็น Bitmap

public Bitmap fetchImage( String imageUrl )
{
    try
    {
        URL url = new URL( imageUrl.trim() ); // imageUrl คือ url ของรูปภาพ
        InputStream input = null;
        URLConnection conn = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection)conn;
    	httpConn.setRequestMethod("GET");
    	httpConn.setReadTimeout(40000); // ตั้งเวลา  connect timeout
    	httpConn.connect(); // connection

    	if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    		input = httpConn.getInputStream(); // จับใส่ InputStream
    	}
    	Bitmap bitmap = BitmapFactory.decodeStream(input); //แปลงเป็น Bitmap
    	input.close();
    	httpConn.disconnect();
        return bitmap;

    }
    catch ( MalformedURLException e ){
    	Log.d("fetchImage",
    			"MalformedURLException invalid URL: " + imageUrl );
    }catch ( IOException e ){
    	Log.d("fetchImage","IO exception: " + e);
    }catch(Exception e){
    	Log.d("fetchImage","Exception: " + e);
    }
    return null;
}

ส่วนที่ 2 จะเป็นส่วนเรียกใช้ เพื่อความเข้าใจต่อผู้อ่านแล้วกัน โดยจะมี 2 วิธีที่สามารถเอาข้อมูล Bitmap ไปใส่ใน ImageView ได้

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    image1 = (ImageView) findViewById(R.id.imageView1);
    image2 = (ImageView) findViewById(R.id.imageView2);

    String imgurl = "http://www.kitco.com/images/live/gold.gif"
    // แบบที่ 1
    image1.setImageBitmap(fetchImage( imgurl ));
    // แบบที่ 2
    image2.setImageDrawable(new BitmapDrawable(fetchImage( imgurl )));
}

Related Posts

Tagged with:  

One Response to Android ดึงภาพจากเว็บมาแสดงใน ImageView

  1. Hmoomay says:

    ได้ความรู้เพิ่มขึ้น ^_____________^

    ** อยากให้เขียน post เพิ่มอีกเรื่อย ๆ น้า ^ ^

    ReplyReply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>