我正在尝试将多个 PNG: 发送到 android 手机。
(每个图像都以单独的 JSON 对象以及与该图像关联的多个其他对象一起发送。)
我以字节数组的形式发送图像,我的手机正在接收它们。
当我尝试使用返回 null
的 BitmapFactory.decodeByteArray
进行解码时,问题就开始了。
我应该如何在服务器端编码并在android端解码?
服务器端的第一次尝试:
File imgPath = new File(path);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] bytes = data.getData();
服务器端的第二次尝试:
byte[] bytes = null;
File file = new File(path);
bytes = Files.readAllBytes(file.toPath());
Android端:
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
从服务器发送 JSON:
public class Response {
List<Person> mPeople;
..other objects...
}
public class Person {
String name;
String image; //base68string
}
public ServerThread {
Response resp = create objects to send;
String str = new Gson().toJson(resp);
OutputStreamWriter.write(str);
}
Android端接收JSON:
Response resp = gson.fromJson(str, Response.class);
List<Person> = resp.getPersons();
//Person-class on the android side is Parcable
所以我尝试了这种方法,但仍然不起作用:
// Server-side
import java.util.Base64;
import java.util.Base64.Encoder;
File file = new File(path);
byte[] bytes = Files.readAllBytes(file.toPath());
Encoder e = Base64.getEncoder();
String base64String = e.encodeToString(bytes);
//Android-side
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
最佳答案
关于java - PNG图像从java服务器到android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41507972/