【问题标题】:How to convert Uri image into Base64?如何将 Uri 图像转换为 Base64?
【发布时间】:2016-10-01 13:56:59
【问题描述】:

我编写了将图像从文件位置转换为 base64 的代码。我可以轻松地将图像从绝对文件位置转换为 base64,例如:C:/Users/Java Engineer/Desktop/test/gallery/magar/Kanuglam.jpg,但我无法从位置转换,例如
.我想从网络服务转换图像以在 android 中使用。 这是代码示例:

/**
 * TEST JSON
 */
String convertToJsonArrayWithImageForMovieDetailTest(ResultSet rs) {

    System.out.println("I am insied json converter");
    JSONArray list = new JSONArray();
    JSONObject obj ;

    //File file;
    File locatedFile;
    FileInputStream fileInputStream;
    try {

        while (rs.next()) {
            obj = new JSONObject();
            System.out.println("inside RS");
            System.out.println("date is there ha ha ");

            obj.put("movie_name", rs.getString("name"));
            obj.put("movie_gener", rs.getString("type"));
            String is_free_stuff = rs.getString("is_free_stuff");
            if (is_free_stuff == "no") {
                is_free_stuff = "PAID";
            } else {
                is_free_stuff = "FREE";
            }
            obj.put("movie_type", is_free_stuff);

            //String movie_image = rs.getString("preview_image");

            //this does not work
            String movie_image = "http://www.hamropan.com/stores/slider/2016-09-10-852311027.jpg";

            //this works for me
        //  file = new File("C:/Users/Java Engineer/Desktop/Nike Zoom Basketball.jpg");
            locatedFile = new File(movie_image);
            // Reading a Image file from file system
            fileInputStream = new FileInputStream(locatedFile);
            if (locatedFile == null) {
                obj.put("movie_image", "NULL");
            } else {
                byte[] iarray = new byte[(int) locatedFile.length()];
                fileInputStream.read(iarray);
                byte[] img64 = com.sun.jersey.core.util.Base64
                        .encode(iarray);
                String imageString = new String(img64);
                obj.put("movie_image", imageString);
            }
            list.add(obj);
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
    return list.toString();
}

这段代码对我有用,但看起来很慢

public String imageConvertMethod(String url) throws Exception{
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try (InputStream input = new URL(url).openStream()) {
        byte[] buffer = new byte[512];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
             output.write(buffer, 0, length);
        }
    }

    byte [] byte_array = output.toByteArray();

    byte[] img64 = com.sun.jersey.core.util.Base64
            .encode(byte_array);
    String  imageString = new String(img64);

    return imageString;
}

【问题讨论】:

  • 你必须先下载文件。
  • 废话。而你的帖子告诉了别的东西。
  • 我的帖子在说什么? @greenapps
  • 它适用于此代码,但速度太慢。 public String lokConvertMethod(String url) throws Exception{ ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream input = new URL(url).openStream()) { byte[] buffer = new byte[512]; for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } } byte [] byte_array = output.toByteArray(); byte[] img64 = com.sun.jersey.core.util.Base64 .encode(byte_array); String imageString = new String(img64); return imageString; }
  • 我们应该读一下吗?在您的帖子中发布代码。它现在无法阅读。

标签: java android web-services


【解决方案1】:

好的,试试这个

bitmap = getBitmapFromUrl(image_url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] array = stream.getByteArray();
encoded_string = Base64.encodeToString(array, 0);

方法wo从url加载图片

public static Bitmap getBitmapFromURL(String src) {
  try {
      URL url = new URL(src);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoInput(true);
      connection.connect();
      InputStream input = connection.getInputStream();
      Bitmap myBitmap = BitmapFactory.decodeStream(input);
      return myBitmap;
  } catch (IOException e) {
     e.printStackTrace();
     return null;
  }
}

【讨论】:

  • 我需要获取图像相对路径,例如:/abc/cba/a.jpg 并将其转换为字符串并将其发送到 android 应用程序。当我使用 c:/abc/cba/a.jpg 时,它可以工作,但 /abc/cba/a.jpg 不起作用。我正在使用位于 D: dir 但图像的 web-service(jersey api)在 C: 所以,我想从我的网络服务应用程序目录中获取图像到另一个相对目录。我尝试使用 Url,但它太慢了,所以需要另一个选项。谢谢
  • 感谢所有试图帮助我的朋友,但我不得不使用其他想法,我将在数据库中将图像保存为 blob 并将其获取到 android 应用程序。
【解决方案2】:

@感谢法比奥·文丘里牧师

试试这个:

ImageUri 到位图:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
        final Uri imageUri = data.getData();
        final InputStream imageStream = getContentResolver().openInputStream(imageUri);
        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
        String encodedImage = encodeImage(selectedImage);
    }
}

用 base64 编码位图

private String encodeImage(Bitmap bm)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);

    return encImage;
}

从 FilePath 编码为 base64

private String encodeImage(String path)
{
    File imagefile = new File(path);
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(imagefile);
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }
    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);
    //Base64.de
    return encImage;

}

输出:

参考: Take picture and convert to Base64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2021-08-23
    • 2020-07-26
    相关资源
    最近更新 更多