首页 文章

Android编码PNG到base64字符串产生无效结果

提问于
浏览
0

该应用程序将base64解码为PNG,但是当我将文件编码回base64以便发送到服务器时,生成的base64是不同的,并且不会生成图像 .

这是原始base64字符串的开头: /9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAYAAIdp

这是从base64和PNG文件编码后的base64的开始: iVBORw0KGgoAAAANSUhEUgAAD8AAAAvQCAIAAABPl1n3AAAAA3NCSVQICAjb4U/gAAAgAElEQVR4nO

这是我用来将文件编码为base64的代码:

BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = true;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inDither = false;

        File file = new File(root +"/saved_images/"+note.imageLocation );
        if(file.exists()){
            // TODO perform some logging or show user feedback
            try {
            Bitmap myBitmap = BitmapFactory.decodeFile(root +"/saved_images/"+note.imageLocation, options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();


            myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            JSONObject object =new JSONObject();
                object.put("image_type", "image/png");
                object.put("image_data", Base64.encodeToString(byteArray, Base64.DEFAULT));


                if (note.serverID == -1) {
                    toReturn.put(String.valueOf(i), object);
                }else{
                    toReturn.put(String.valueOf(note.serverID), object);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            i--;
        }else{
            Log.i("File Not Found", "NoteModel - "+file);
        }

3 回答

  • 1

    如果您确实收到了base64字符串并将其解码为png字节而不使用中间Bitmap而保存到文件中,那么您应该将该png文件加载到字节缓冲区中并将该字节缓冲区编码为您将上载的base64字符串 .

    如果您确实使用了位图来保存图像,那么这是一个坏主意 .

    不要使用类 BitmapBitmapFactory 来上载和下载文件 . 你将得到不同的图像 .

  • 0

    试试我的solution,它解释了如何将位图编码为base64并将base64成功解码回位图 .

  • 1

    请试试这段代码,

    public String encodeToBase64(Bitmap image) {
        Bitmap immagex = Bitmap.createScaledBitmap(image, 350, 350, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
        Log.e("LOOK", imageEncoded);
        return "data:image/png;base64," + imageEncoded.replace(" ", "").replace("\n", "");
    }
    
    public Bitmap encodeToBitmap(String encodedImage) {
        encodedImage = encodedImage.substring(encodedImage.indexOf(",") + 1);
        byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return bitmap;
    }
    

相关问题