Send a .jpg image to Web Service from an Android Device

254 Views Asked by At

I need to send jpg images from my android app to my web service and store it in my database. I'm using android studio and my web service is Php Rest with a slim framework. I reallly have no idea what to do.

1

There are 1 best solutions below

0
On BEST ANSWER

I do the same a few days ago... I do this:

  • Convert image to Base64 (byte array => byte[])

  • Conver byte[] to String

  • Send String with httpPost to server

And this is my code to convert image:

public String formatPhoto_JPEGtoByteArray (String uri){
    // Read bitmap from file
    Bitmap bitmap = null;
    InputStream stream = null;
    ByteArrayOutputStream byteStream = null;

    try {
        stream = new BufferedInputStream(new FileInputStream(new File(uri)));
        bitmap = BitmapFactory.decodeStream(stream);

        byteStream = new ByteArrayOutputStream();
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, byteStream);

        // Convert ByteArrayOutputStream to byte array. Close stream.
        byte[] byteArray = byteStream.toByteArray();

        Log.e("-- FilesAndFolders.formatPhoto_JPEGtoByteArray --","Last file of size: " + byteArray.length);

        //160 kb = 163840 bytes
        //if(byteArray.length == 163840){
        //    //Declaration of variables
        //    int tantXcent = (160 * 100) / byteArray.length;

        //    byteStream = new ByteArrayOutputStream();
        //    bitmap.compress(Bitmap.CompressFormat.JPEG, tantXcent, byteStream);

        //    // Convert ByteArrayOutputStream to byte array. Close stream.
        //    byteArray = byteStream.toByteArray();
        //    Log.e("-- FilesAndFolders.formatPhoto_JPEGtoByteArray --","Actual size of file: " + byteArray.length );
        //}

        String imageEncoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);

        byteStream.close();
        byteStream = null;

        return imageEncoded;
    }
    catch (IOException ex) {
        Log.e("-- GeneralMethods.formatPhoto --", "Exception with " + uri,ex);
        return null;
    }
    catch (Exception ex){
        Log.e("-- GeneralMethods.formatPhoto --", "Exception with " + uri,ex);
        return null;
    }
    finally {
        try {
            if (stream != null) stream.close();
            if (byteStream != null) byteStream.close();
        } catch (Exception e) {}
    }
}

Tell me if I helped you and good programming!