-1

I want to fill an ImageView with an image saved on my localhost. I can display it in a browser fine but it doesn't get displayed in my ImageView.

PHP script to display image:

<?php
include('connect_db.php');

    $id = $_GET['id'];

    $path = 'Profile_Images/'.$id.'.jpg';

        echo '<img src='.$path.' border=0>';

?>

Here is my android code to download an image from a URL:

URL url;
try {
    url = new URL("http://192.168.1.13/get_profile_image.php?id=145");
    new DownloadImage(this).execute(url);
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

@Override
public void imageDownloaded(final Bitmap downloadedImage) {

runOnUiThread(new Runnable() {
     public void run() {

        ImageView imageView = (ImageView)findViewById(R.id.imageView);
        imageView.setImageBitmap(downloadedImage);
    }
});
}

When I put the URL to some other image it works fine but mine never gets loaded, any ideas?

Also, the following code works but I have a feeling its bad practice..

    URL url;
    try {
        url = new URL("http://192.168.1.13/Profile_Images/145.jpg");
        new DownloadImage(this).execute(url);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Where 145 would be a variable.

Edit

Any reasons for the down-votes would be appreciated!

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
TomSelleck
  • 6,706
  • 22
  • 82
  • 151

2 Answers2

3

It's pretty simple, actually. When you send a request to http://192.168.1.13/get_profile_image.php?id=145 a string (<img src=Profile_Images/'.$id.'.jpg border=0>) is sent back. Because the DownloadImage class doesn't parse HTML (it wants raw image data) it doesn't know where the actual image is. Two solutions:

  1. Your 'bad practice' approach
  2. Use this PHP script instead to echo the raw image data:

PHP:

$id = $_GET['id'];
$path = 'Profile_Images/'.$id.'.jpg';

$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($path));
readfile($path);

EDIT: forgot to credit someone: the above code is taken from here (with adapted variable names): https://stackoverflow.com/a/1851856/1087848

Community
  • 1
  • 1
11684
  • 7,356
  • 12
  • 48
  • 71
2

Your PHP code will print out something along the lines of:

<img src=Profile_Images/145.jpg border=0>

Not only is this malformed HTML, but it is a text output. Your other URL, http://192.168.1.13/Profile_Images/145.jpg points to an image file, from which the data your receive is an image, not an HTML string.

You should consider having your PHP return a JSON response with the URL of the image ID, and then running DownloadImage on that URL. The advantage this has over a raw echo is that you can easily expand the solution to return other types of files, and even return an array of files.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195