将图像动态转换为二进制,反之亦然

Sil*_*ler 4 android image

如何将图像转换为二进制数据 .. ???

我想将转换后的二进制数据发送到另一台设备或Web服务器.

哪种机制最好这样做.

Sum*_*ant 9

图像位于Bitmap中,然后使用以下代码将该图像转换为二进制.通过使用以下代码

Bitmap photo;// this is your image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Run Code Online (Sandbox Code Playgroud)

要从Binary获取Image,请使用以下示例:

Bitmap bMap = null;

bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
Run Code Online (Sandbox Code Playgroud)


Sil*_*ler 6

我找到了将图像上传到服务器的一个很好的例子.

  • 在做任何事之前创建一个位图变量.
  • 变量将图像名称设置为SD卡.
  • 这个变量,你必须放置文件的路径,这取决于你.
  • sendData是函数名,要调用它,你可以使用类似的东西 sendData(null).
  • 记得将它包装成try catch.

private Bitmap bitmap;
public static String exsistingFileName = "";

public void sendData(String[] args) throws Exception {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();

        // here, change it to your php;
        HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        bitmap = BitmapFactory.decodeFile(exsistingFileName);

        // you can change the format of you image compressed for what do you want;
        // now it is set up to 640 x 480;
        Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // CompressFormat set up to JPG, you can change to PNG or whatever you want;
        bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();

        // sending a String param;
        entity.addPart("myParam", new StringBody("my value"));

        // sending a Image;
        // note here, that you can send more than one image, just add another param, same rule to the String;
        entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost, localContext);
        BufferedReader reader = new BufferedReader(new InputStreamReader(   response.getEntity().getContent(), "UTF-8"));
        String sResponse = reader.readLine();

    } catch (Exception e) {
        Log.v("myApp", "Some error came up");
    }
}
Run Code Online (Sandbox Code Playgroud)