从 Android 设备向 Web 服务发送 .jpg 图像

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

我需要将 jpg 图像从我的 android 应用程序发送到我的网络服务并将其存储在我的数据库中。我正在使用 android studio,我的 Web 服务是 Php 使用一个精简的框架休息一下。我真的不知道该怎么办。

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

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

  • 将字节[]转换为字符串

  • 使用 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) {}
    }
}

如果我帮助了你,请告诉我,好的编程!