如何将图像转换为二进制数据 .. ???
我想将转换后的二进制数据发送给 另一台设备或网络服务器。
最好采用哪种机制。?
答案 0 :(得分:9)
图像位于Bitmap中,然后使用以下代码将该图像转换为二进制。使用以下代码
Bitmap photo;// this is your image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
要从二进制文件获取图像,请使用以下示例:
Bitmap bMap = null;
bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
答案 1 :(得分:6)
我找到了一个将图像上传到服务器的好例子。
sendData(null)
。
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");
}
}
答案 2 :(得分:2)
试试这个
让img
包含位图图像
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
imageInByte
现在包含位图图像的字节数据。
转换逆转
Bitmap bp = BitmapFactory.decodeByteArray(imgArray, 0,imgArray.length);
希望这可以帮到你
答案 3 :(得分:1)
如果您想使用HttpPost
HttpClient
请求