无法将base64转换后的图像发布到休息服务 [英] unable to post base64 converted image to rest service

查看:106
本文介绍了无法将base64转换后的图像发布到休息服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个代码,从库中选择 image 并将其转换为 BASE64字符串。由于所选图像太大,字符串太大而无法发布。

I've written a code that selects image from gallery and convert it into a BASE64 string. as the selected images was too large the string is too big to be posted.

我压缩了图像,以便减少字符串的长度。但仍然是字符串的长度仍然很大。

I have compressed the image so that the length of the string could be reduced. but still the length of the string is still large.

我使用的代码如下,
这个函数将所选图像设置为 imageView

The code that i used is as follows, This function sets the selected image in an imageView and

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        sPicturePath = cursor.getString(columnIndex);
        cursor.close();
        imageView = (ImageView) findViewById(R.id.imageView);

        Bitmap bm = ShrinkBitmap(sPicturePath, 300, 300);
        imageView.setImageBitmap(bm);

        /**
         * Compute size of the image selected image
         */
        File file = new File(sPicturePath);
        if (file.exists()) {

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            System.out.println("megabytes : " + megabytes);
            Log.d("size", String.valueOf(megabytes));
        }

        imageView.setImageBitmap(BitmapFactory.decodeFile(sPicturePath));

        Bitmap bm1 = BitmapFactory.decodeFile(sPicturePath);
        //CropImage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm1.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
        byte[] byteArrayImage = baos.toByteArray();

        encodedString = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
        //Toast.makeText(getApplicationContext(), encodedString, Toast.LENGTH_SHORT).show();
        String length = String.valueOf(encodedString.length());
        //Toast.makeText(getApplicationContext(),lenght,Toast.LENGTH_SHORT).show();

        Log.d("encodedString", encodedString);
        Log.d("length", length);

ShrinkBitmap.java

ShrinkBitmap.java

Bitmap ShrinkBitmap(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;
}

我想要实现的是选择图像来自gallery的将其转换为 BASE64字符串并通过 REST服务发布。

What i want to achieve is to select an image from gallery convert it into a BASE64 string and post it through a REST service.

推荐答案

GET请求具有URL长度限制。您需要使用使用 HttpURLConnection 使用 MultipartEntity 发送文件。您需要创建一个帖子请求。

A GET request has URL length restrictions. You need to send the file using MultipartEntity using HttpURLConnection. You need to create a post request.

如果你的文件名是image.jpg。

If your filename is image.jpg.

Bitmap bitmap = ...;
String filename = "image.jpg";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("picture", contentPart);
String response = multipost("http://server.com", reqEntity);

这是多重邮件功能。

private static String multipost(String urlString, MultipartEntity reqEntity) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
        conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

        OutputStream os = conn.getOutputStream();
        reqEntity.writeTo(conn.getOutputStream());
        os.close();
        conn.connect();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(conn.getInputStream());
        }

    } catch (Exception e) {
        Log.e(TAG, "multipart post error " + e + "(" + urlString + ")");
    }
    return null;        
}

private static String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return builder.toString();
}

这个 SO线程。

这篇关于无法将base64转换后的图像发布到休息服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆