我正在编码一个函数,该函数在android应用程序中将图像编码为Base64字符串,并将此字符串发送到服务器以写入文件。它可以写一个文件,但它只是图像的一部分。这是我的代码:
此代码用于获取图像的列表位图:
for (int i = 0; i < mArrayUri.size(); i++) {
lstBitmapImg.add(MediaStore.Images.Media.getBitmap(this.getContentResolver(), mArrayUri.get(i)));
}
此处的编码代码:
@Override
protected Void doInBackground(Void... voids) {
System.out.println("Size=>>>>>>>>" + lstImgBitmap.size());
for (int i = 0; i < lstImgBitmap.size(); i++) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
lstImgBitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.NO_WRAP | Base64.URL_SAFE);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.encodedAuthority("192.168.56.1:8080/HelloRESTful/rest")
.appendPath("image_service")
.appendPath("upload")
.appendPath(lstImgName.get(i))
.appendPath(encodedImage);
String url = builder.build().toString();
HttpHandler httpHandler = new HttpHandler();
httpHandler.makeServiceCall(url, "POST");
}
return null;
}
这是要写入文件的代码:
@Path("/image_service")
public class ImageService {
@Path("/upload/{imageName}/{encodeImage}")
@POST
public String uploadImage(@PathParam("imageName") String imgName, @PathParam("encodeImage") String encodeImage) {
System.out.println(encodeImage);
try {
upload(imgName, encodeImage);
} catch (IOException ex) {
Logger.getLogger(ImageService.class.getName()).log(Level.SEVERE, null, ex);
return ex.toString();
}
return "Success";
}
public void upload(String imgName, String encodeImage) throws FileNotFoundException, IOException {
BufferedImage image;
try (ByteArrayInputStream decodeBytes = new ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64(encodeImage))) {
image = ImageIO.read(decodeBytes);
}
File file = new File("C:\\Users\\Asus\\Documents\\NetBeansProjects\\HelloRESTful\\src\\main\\resources\\images\\" + imgName + ".jpg");
ImageIO.write(image, "jpg", file);
}
}
这是上传的结果:
[{ 1