为什么我从同一张图片(Android Studio和Netbeans)中得到2个不同的base64编码字符串?

时间:2018-12-26 00:23:48

标签: java android base64

我需要将从图库中选择的图像转换为base64字符串。 然后,我将baase64字符串作为API请求的参数传递。 只有一个问题。当我使用netbeans时,它可以工作,而当我使用Android Studio时,则不能。我发现问题是base64字符串输出。我不知道为什么,如果我使用完全相同的图像,输出将不同。 也许是因为我必须使用相同的确切方法读取图像文件而导致问题出现了??

那是我在Netbeans(工作)中的代码:

    InputStream inputStream = new FileInputStream("testImage.jpg");
    byte[] bytes;
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    bytes = output.toByteArray();
    String encodedFile = Base64.getEncoder().encodeToString(bytes);

这就是Android Studio中的代码:

            Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageData = baos.toByteArray();
            InputStream inputStream = getContentResolver().openInputStream(imageUri);

            byte[] buffer_new = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer_new)) != -1) {
                    output.write(buffer_new, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            String encodedImage = Base64.encodeToString(bytes,Base64.DEFAULT);
            Log.v("encodedImage", encodedImage);

输出字符串仅在第一个字符处几乎是相同的。然后它们是不同的..使用android studio编码的字符串,当我尝试使用API​​时遇到此错误。

BAD_ARGUMENTS:<key>
Error while parsing some arguments. This error may be caused by illegal type or length of argument.

我应该使用什么来获得相同的base64字符串? ps。在Netbeans中,图像是项目同一文件夹中的文件,在android studio中,用户可以从图库中加载图片。

0 个答案:

没有答案