【问题标题】:How can I convert an image into a Base64 string?如何将图像转换为 Base64 字符串?
【发布时间】:2011-06-17 08:57:14
【问题描述】:

将图像(最大 200 KB)转换为 Base64 字符串的代码是什么?

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

我在 Google 和 Stack Overflow 中搜索,但找不到我能负担得起的简单示例,并且我还找到了一些示例,但它们并不是在谈论转换为字符串。然后我需要转换成一个字符串通过 JSON 上传到我的远程服务器。

【问题讨论】:

    标签: android base64


    【解决方案1】:

    Kotlin 版本:

    fun File.toBase64(): String? {
     val result: String?
     inputStream().use { inputStream ->
        val sourceBytes = inputStream.readBytes()
        result = Base64.encodeToString(sourceBytes, Base64.DEFAULT)
     }
    
     return result
    }
    

    【讨论】:

      【解决方案2】:

      我做了一个静态函数。我认为它更有效。

      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;
      
          }
      

      简单易行!

      【讨论】:

      • 它正在向字符串添加下一行,我们可以克服这个问题吗?
      • getting java.io.FileNotFoundException: /storage/emulated/0/1417462683.jpg(没有这样的文件或目录)即使文件路径正确
      【解决方案3】:

      对于那些正在寻找一种将图像文件转换为 Base64 字符串而不进行压缩或先将文件转换为位图的有效方法的人,您可以改为 encode the file as base64

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

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        这是图像编码和图像解码的代码。

        在 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();
        

        【讨论】:

        • 这真的会编译吗?你遗漏了什么吗?
        【解决方案5】:

        在 Android 中将图像转换为 Base64 字符串:

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        

        【讨论】:

          【解决方案6】:

          这是Kotlin中的编码和解码代码:

           fun encode(imageUri: Uri): String {
              val input = activity.getContentResolver().openInputStream(imageUri)
              val image = BitmapFactory.decodeStream(input , null, null)
          
              // Encode image to base64 string
              val baos = ByteArrayOutputStream()
              image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
              var imageBytes = baos.toByteArray()
              val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
              return imageString
          }
          
          fun decode(imageString: String) {
          
              // Decode base64 string to image
              val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
              val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
          
              imageview.setImageBitmap(decodedImage)
          }
          

          【讨论】:

            【解决方案7】:

            以下是可能对您有所帮助的伪代码:

            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;
            }
            

            【讨论】:

              【解决方案8】:

              使用此代码:

              byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
              
              Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
              

              【讨论】:

              • 这正好相反
              【解决方案9】:
              // Put the image file path into this method
              public static String getFileToByte(String filePath){
                  Bitmap bmp = null;
                  ByteArrayOutputStream bos = null;
                  byte[] bt = null;
                  String encodeString = null;
                  try{
                      bmp = BitmapFactory.decodeFile(filePath);
                      bos = new ByteArrayOutputStream();
                      bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                      bt = bos.toByteArray();
                      encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
                  }
                  catch (Exception e){
                    e.printStackTrace();
                  }
                  return encodeString;
              }
              

              【讨论】:

                【解决方案10】:

                这段代码在我的项目中运行完美:

                profile_image.buildDrawingCache();
                Bitmap bmap = profile_image.getDrawingCache();
                String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);
                
                
                public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(CompressFormat.JPEG, 70, stream);
                    byte[] byteFormat = stream.toByteArray();
                
                    // Get the Base64 string
                    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
                
                    return imgString;
                }
                

                【讨论】:

                  【解决方案11】:

                  除了使用Bitmap,您还可以通过一个简单的InputStream 来执行此操作。嗯,我不确定,但我认为它有点效率。

                  InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
                  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 encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
                  

                  【讨论】:

                  • 当然这样更有效率;只是将文件转换为其 base64 表示,并避免对图像进行绝对无意义的重新压缩。
                  • 这里的fileName是文件的路径还是实际的文件名???请不要忘记标记我:) 谢谢。
                  • @user2247689 当您尝试访问文件时,显然您必须提供文件的完整路径,包括其名称。如果文件与源程序所在的路径相同,则文件名就足够了。
                  • 一个问题,这里的“8192”是什么意思,是文件大小还是什么?
                  • 这段代码不起作用,浪费了我很多时间来解决这个问题。
                  【解决方案12】:

                  如果您需要基于 JSON 的 Base64,请查看 Jackson:它在低级别(JsonParser、JsonGenerator)和数据绑定级别都明确支持二进制数据作为 Base64 读/写。所以你可以只使用带有 byte[] 属性的POJOs,并自动处理编码/解码。

                  而且效率也很高,如果这很重要的话。

                  【讨论】:

                  • 对我来说太难了,我的技能很低,我在谷歌上查了一下,找不到简单的例子......也许如果你能给我像 xil3 这样的代码例子,我会明白的
                  【解决方案13】:

                  您可以使用 Base64 Android 类:

                  String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
                  

                  不过,您必须将图像转换为字节数组。这是一个例子:

                  Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
                  byte[] b = baos.toByteArray();
                  

                  * 更新 *

                  如果您使用的是较旧的 SDK 库(因为您希望它在具有较旧版本操作系统的手机上工作)您将不会打包 Base64 类(因为它刚刚在 API 级别 8 AKA 版本中出现2.2)。

                  查看这篇文章以了解解决方法:

                  How to base64 encode decode Android

                  【讨论】:

                  • 好的,我可以使用 PHP+JSON 将该字符串 (encondedImage) 放入远程数据库列 ????哪种类型必须是数据库的列? VARCHAR?
                  • 好吧,使用 VARCHAR 你需要指定它有多大,所以也许 TEXT 会更好。图片可以是任意大小范围...
                  • 替换后我正在工作:String encodedImage = Base64.encode(byteArrayImage, Base64.DEFAULT); By: String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
                  • 有没有人意识到这种方法对文件进行了无意义的重新压缩?为什么这么赞成? Chandra Sekhar 的回答是最有效的。
                  • ElYeante - 你说得对,这是一种更有效的方法。
                  【解决方案14】:

                  如果您在 Android 上执行此操作,这里有一个从 React Native codebase 复制的助手:

                  import java.io.ByteArrayOutputStream;
                  import java.io.Closeable;
                  import java.io.FileInputStream;
                  import java.io.FileNotFoundException;
                  import java.io.IOException;
                  import java.io.InputStream;
                  
                  import android.util.Base64;
                  import android.util.Base64OutputStream;
                  import android.util.Log;
                  
                  // You probably don't want to do this with large files
                  // (will allocate a large string and can cause an OOM crash).
                  private String readFileAsBase64String(String path) {
                    try {
                      InputStream is = new FileInputStream(path);
                      ByteArrayOutputStream baos = new ByteArrayOutputStream();
                      Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
                      byte[] buffer = new byte[8192];
                      int bytesRead;
                      try {
                        while ((bytesRead = is.read(buffer)) > -1) {
                          b64os.write(buffer, 0, bytesRead);
                        }
                        return baos.toString();
                      } catch (IOException e) {
                        Log.e(TAG, "Cannot read file " + path, e);
                        // Or throw if you prefer
                        return "";
                      } finally {
                        closeQuietly(is);
                        closeQuietly(b64os); // This also closes baos
                      }
                    } catch (FileNotFoundException e) {
                      Log.e(TAG, "File not found " + path, e);
                      // Or throw if you prefer
                      return "";
                    }
                  }
                  
                  private static void closeQuietly(Closeable closeable) {
                    try {
                      closeable.close();
                    } catch (IOException e) {
                    }
                  }
                  

                  【讨论】:

                  • (会分配大字符串,会导致OOM崩溃)那么这种情况下的解决方法是什么?
                  【解决方案15】:
                  byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);
                  

                  【讨论】:

                  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
                  • 解释一下。
                  猜你喜欢
                  • 1970-01-01
                  • 2018-09-07
                  • 2014-07-21
                  • 2020-12-22
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-04-19
                  相关资源
                  最近更新 更多