从Android设备发送.jpg图像到Wb服务

时间:2015-06-18 13:56:24

标签: php android rest slim

我需要将我的Android应用程序中的jpg图像发送到我的Web服务并将其存储在我的数据库中。我使用的是android studio,而我的网络服务是Php Rest,它采用纤薄的框架。我完全不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我几天前也这样做......我这样做:

  • 将图像转换为Base64(字节数组=> byte [])

  • Conver byte [] to String

  • 使用httpPost将字符串发送到服务器

这是我转换图片的代码:

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) {}
    }
}

告诉我,如果我帮助你并做好编程!