如何将Uri图像转换为Base64?

时间:2016-10-01 13:56:59

标签: java android web-services

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

#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;

char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}   
int length = 0;
while(name[length] != '\0')
{
length++;
}
                    for(n=0; n<4; n++)
                {
                            if (strncmp(ptr, "snit", 4) == 0)
                            {
            cout << "you found the snitch "    <<        ptr[i];
                            }
                }
cout<<name <<"is"<<length<<"chars long";
}

这段代码对我有用但似乎很慢

/**
 * 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();
}

2 个答案:

答案 0 :(得分: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);

方法从网址加载图片

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

答案 1 :(得分:0)

@thanks to Fabio Venturi Pastor

试试这个:

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;

}

输出

enter image description here

参考: Take picture and convert to Base64