如何将图像转换为Base64字符串?

161

如何将一张图片(最大200KB)转换成 Base64 字符串?

我需要知道在 Android 中如何实现这个功能,因为我需要在我的主要应用程序中添加上传图片到远程服务器的功能,并将它们作为字符串放入数据库的一行中。

我已经在 Google 和 Stack Overflow 上搜索了很久,但是没有找到易于理解的示例代码。虽然我找到了一些示例代码,但它们并没有讲述如何将图片转换成字符串。所以我需要将它们转换成字符串后通过 JSON 上传到远程服务器。

18个回答

1

对于那些想要将图像文件转换为Base64字符串的人,而不需要压缩或先将文件转换为位图的高效方法,您可以选择将文件编码为base64

val base64EncodedImage = FileInputStream(imageItem.localSrc).use {inputStream - >
    ByteArrayOutputStream().use {outputStream - >
            Base64OutputStream(outputStream, Base64.DEFAULT).use {
                base64FilterStream - >
                    inputStream.copyTo(base64FilterStream)
                base64FilterStream.flush()
                outputStream.toString()
            }
      }
}

希望这有所帮助!

0
以下是可能对您有所帮助的伪代码:
public  String getBase64FromFile(String path)
{
    Bitmap bmp = null;
    ByteArrayOutputStream baos = null;
    byte[] baat = null;
    String encodeString = null;
    try
    {
        bmp = BitmapFactory.decodeFile(path);
        baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        baat = baos.toByteArray();
        encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

   return encodeString;
}

0

为编码而用

 private String encodeImage(Bitmap bitmap){
        int previewWidth=150;
        int previewHeight=bitmap.getHeight()*previewWidth/ bitmap.getWidth();
        Bitmap previewBitmap = Bitmap.createScaledBitmap(bitmap,previewWidth,previewHeight,false);
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        previewBitmap.compress(Bitmap.CompressFormat.JPEG,50,byteArrayOutputStream);
        byte[] bytes=byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(bytes,Base64.DEFAULT);
    }


private final ActivityResultLauncher<Intent> pickImage=registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (result.getResultCode()==RESULT_OK){
                if (result.getData()!=null){
                    Uri imageuri=result.getData().getData();
                    try{
                        InputStream inputStream= getContentResolver().openInputStream(imageuri);
                        Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
                        binding.imageProfile.setImageBitmap(bitmap);
                        encodedImage= encodeImage(bitmap);
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
            }
        }
);

0
在 Kotlin 中,您可以直接使用 decode 函数来处理 byteArray...
  private fun stringToBitmap(encodedString: String): Bitmap {
    val imageBytes = decode(encodedString, DEFAULT)
    return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}

0
这是关于图像编码和解码的代码。
在一个XML文件中。
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yyuyuyuuyuyuyu"
    android:id="@+id/tv5"
/>

在一个Java文件中:
TextView textView5;
Bitmap bitmap;

textView5 = (TextView) findViewById(R.id.tv5);

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);

new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... voids) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] byteFormat = stream.toByteArray();

        // Get the Base64 string
        String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

        return imgString;
    }

    @Override
    protected void onPostExecute(String s) {
       textView5.setText(s);
    }
}.execute();

这能编译通过吗?你有漏掉什么吗? - Peter Mortensen

0
byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

6
虽然这段代码可能能回答问题,但是提供关于为什么和/或如何回答问题的额外背景信息可以提高其长期价值。 - Donald Duck
需要解释一下。 - Peter Mortensen

0

我写了一个静态函数。我认为这样更有效率。

public static String file2Base64(String filePath) {
        FileInputStream fis = null;
        String base64String = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024 * 100];
            int count = 0;
            while ((count = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, count);
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        base64String = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
        return base64String;

    }

简单而更容易!


它正在向字符串中添加下一行,我们能够克服这个问题吗? - GvSharma
即使文件路径正确,仍会出现java.io.FileNotFoundException:/storage/emulated/0/1417462683.jpg(没有这样的文件或目录)的错误。 - Annie

-2
请使用以下代码:
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

这恰恰相反。 - Rafael Ruiz Muñoz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接