通过Spring Rest将图像上传为byte []

时间:2018-01-18 04:35:32

标签: java spring spring-mvc

我正在尝试将图片文件上传为byte[]对象。在Web服务上,将此byte[]转换为BufferedImage并执行一些处理,然后返回byte[]作为对客户端的响应。

但是在调用ImageIO.read(byte[] input)时我总是得到空指针。我注意到调用服务之前和之后的byte[]长度是不同的。请帮忙。遵循客户端和其他Web服务的代码。

客户端代码:     CloseableHttpClient httpclient = null;

    final String uri = "http://localhost:8080/core/uploadForMarkImg";

    File source_imgFile = new File("C:\\watermarktest\\source.jpg");


    try
    {
    ImageInputStream iis = ImageIO.createImageInputStream(source_imgFile);

    Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);

    while (imageReaders.hasNext()) {
        ImageReader reader = (ImageReader) imageReaders.next();
        System.out.printf("formatName: %s%n", reader.getFormatName());
    }
    }catch (Exception ex)
    {
        ex.printStackTrace();
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {

    BufferedImage img=ImageIO.read(source_imgFile);
    ImageIO.write(img, "jpg", bos);
    bos.flush();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }

httpclient = HttpClients.custom().build();
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody(
            "imgFile", bos.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, source_imgFile.getName()).build();

    post.setEntity(entity);

服务器代码:

@RequestMapping(value = "/uploadForMarkImg", method = RequestMethod.POST, consumes = { "application/octet-stream" })
public ResponseEntity<byte[]> imgMark(@RequestBody byte[] imgFile) {


    try {
        ClassLoader classLoader = getClass().getClassLoader();
        File watermarkImageFile = new File(classLoader.getResource("watermark.png").getFile());


        System.out.println("input file length " + imgFile.length);
        BufferedImage resizeOriginal = null;
        InputStream inputStream = new ByteArrayInputStream(imgFile);
        BufferedImage sourceImage=ImageIO.read(new ByteArrayInputStream(imgFile));
System.out.println("converted to buffer image completed for source image " + sourceImage);

        BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);

        System.out.println("converted to buffer image completed for watermark image " + watermarkImageFile);

        System.out.println("SouceImage Size Width: " + sourceImage.getWidth());
        System.out.println("SouceImage Size Height: " + sourceImage.getHeight());

sourceImage.get将始终获得nullpointer errror。

1 个答案:

答案 0 :(得分:0)

根据代码,您尝试在imgFile multipart下编写图像字节。因此,当您想要检索这些字节时,它应该通过该部分本身。

试试这个:

@RequestMapping(value = "/uploadForMarkImg", method = RequestMethod.POST, consumes = { "application/octet-stream" })
public ResponseEntity<byte[]> imgMark(@RequestParam(value="imgFile") MultipartFile[] files) {

第一个元素会给你文件。或者可能根本不需要数组。试试这个。