发送base64字符串到服务器大小不正确

时间:2018-06-21 11:38:49

标签: android image base64

我一直在尝试使用发布请求将图像上传到网络服务器。为了易于处理,我将图像更改为base64字符串。当我记录base64字符串时,我可以看到它大约是4000-5000个字符。但是,当我在服务器上收到它时,我将其写入txt文件以查看得到的结果。但是大小超过一百万个字符。只是似乎无法找出问题所在。由于某种原因,服务器接收到太多信息。流或文件大小有问题吗?我需要发送完整的图片。

    private String encodedImage(Bitmap bitmap){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] bytes = baos.toByteArray();
    String encImage = Base64.encodeToString(bytes,0 ,bytes.length ,Base64.DEFAULT);
    return encImage;
}

/**
 * On activity result will launch when activity gives a result back.
 * @param requestCode, code to check for specific request
 * @param resultCode, code to correspond for result
 * @param data, intent that gives back result.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == IMAGE_RESULT_CODE && resultCode == RESULT_OK){
        // Set the imageview to blank ot fix caching errors
        imageView.setImageDrawable(null);

        //Get file
        File image = new File(Environment.getExternalStorageDirectory(), "StendeNav/Startpunt.jpeg");
        Uri imageUri = Uri.fromFile(image);

        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // set imageview


        String base64 = encodedImage(bitmap);

        //decode base64 string to image
        byte[] imageBytes = Base64.decode(base64, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        imageView.setImageBitmap(decodedImage);

        String urlIn = "http://192.168.43.7/uploadimage.php";
        String urlParameters = "image=" + base64;

        new uploadBase().execute(urlIn,urlParameters);
    }
}
private String httpPOST(String urlIn, String urlParameters, Context context){

    StringBuffer data = new StringBuffer("");
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;
    try{
        URL url = new URL(urlIn);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty( "Charset", "UTF-8");
        connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
            wr.write( postData );
        }

        InputStream inputStream = connection.getInputStream();

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        while ((line = rd.readLine()) != null) {
            data.append(line);
        }

    } catch (IOException e) {
        // writing exception to log
        Log.d("Bullshit",e.toString());
    }

    return data.toString();
}

public class uploadBase extends AsyncTask<String, Void, String>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        StringBuffer data = new StringBuffer("");
        byte[] postData       = strings[1].getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;

        try{
            URL url = new URL(strings[0]);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty( "Charset", "UTF-8");
            connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
            try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
                wr.write( postData );
            }

            InputStream inputStream = connection.getInputStream();

            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = rd.readLine()) != null) {
                data.append(line);
            }

        } catch (IOException e) {
            // writing exception to log
            Log.d("Bullshit",e.toString());
        }

        return data.toString();        }

    @Override
    protected void onPostExecute(String s) {
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试使用此功能转换位图

public static String convertBitmapToBase64( Bitmap photo) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);

    byte[] imageBytes = baos.toByteArray();
    return Base64.encodeToString(imageBytes, Base64.NO_WRAP);
}

答案 1 :(得分:0)

onActivityResult()

File file = new File(getPathFromUri(data.getData()));
                path = file.toString();
                Bitmap bm = shrinkImage(path,300,300);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
                byte[] b = outputStream.toByteArray();
                imageString = Base64.encodeToString(b,Base64.DEFAULT);
                imgProfileCircle.setImageBitmap(bm);
                bm.recycle();

private Bitmap shrinkImage(String file, int width, int height) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
        int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);

        if (heightRatio > 1 || widthRatio > 1)
        {
            if (heightRatio > widthRatio)
            {
                bmpFactoryOptions.inSampleSize = heightRatio;
            } else {
                bmpFactoryOptions.inSampleSize = widthRatio;
            }
        }

        bmpFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
        return bitmap;
    }