views:

45

answers:

1

I'm having trouble getting the compressed jpeg image (stored as a blob in my database).

here is the snippet of code I use to output the image that I have in my database:


if($row = mysql_fetch_array($sql))
{
    $size = $row['image_size'];
    $image = $row['image'];
    if($image == null){
        echo "no image!";
    } else {
       header('Content-Type: content/data');
       header("Content-length: $size");
       echo $image;
    }
}

here is the code that I use to read in from the server:


        URL sizeUrl = new URL(MYURL);
        URLConnection sizeConn = sizeUrl.openConnection();

        // Get The Response
        BufferedReader sizeRd = new BufferedReader(new InputStreamReader(sizeConn.getInputStream()));
        String line = "";
        while(line.equals("")){
            line = sizeRd.readLine();
        }
        int image_size = Integer.parseInt(line);

        if(image_size == 0){
            return null;
        }

        URL imageUrl = new URL(MYIMAGEURL);
        URLConnection imageConn = imageUrl.openConnection();

        // Get The Response
        InputStream imageRd = imageConn.getInputStream();


        byte[] bytedata = new byte[image_size];
        int read = imageRd.read(bytedata, 0, image_size);

        Log.e("IMAGEDOWNLOADER", "read "+ read + " amount of bytes");
        Log.e("IMAGEDOWNLOADER", "byte data has length " + bytedata.length);

        Bitmap theImage = BitmapFactory.decodeByteArray(bytedata, 0, image_size);
        if(theImage == null){
            Log.e("IMAGEDOWNLOADER", "the bitmap is null");
        }
        return theImage;

My logging shows that everything has the right length, yet theImage is always null. I'm thinking it has to do with my content type. Or maybe the way I'm uploading?

A: 

Try this function. It works for me:

Bitmap loadPhotoBitmap(URL url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {

        FileOutputStream fos = new FileOutputStream("/sdcard/photo-tmp.jpg");
        BufferedOutputStream bfs = new BufferedOutputStream(fos);

        in = new BufferedInputStream(url.openStream(),
                IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);                    
        out.flush();
        final byte[] data = dataStream.toByteArray();

        bfs.write(data, 0, data.length);
        bfs.flush();

        BitmapFactory.Options opt = new BitmapFactory.Options();
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not load file: " + this, e);
    } finally {
        closeStream(in);
        closeStream(out)
        closeStream(bfs);
    }

    return bitmap;
}
what is the copy method that you're using?
Kareem