如何在java中获取图像大小

时间:2015-10-28 04:06:00

标签: java spring spring-mvc

应用程序想要检查现有的上传图像,是否超过最大限制。

这是控制器

@RequestMapping(value = "/product/{id}/{id2}", method = RequestMethod.GET,
      produces = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public RestMethod validateFileSize(HttpSession session, 
          @PathVariable("id") String fileName, @PathVariable("id2") String fileType) throws Exception {
      if (!fileName.isEmpty()) {
        URL url = new URL("http://localhost:8080/MyShop/image/" + fileName + "." + fileType +"/");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = url.openStream();
        byte[] b = new byte[2^16];
        int read = is.read(b);

        while (read > -1) {
            baos.write(b, 0, read);
            read = is.read(b);
        }

        int size = baos.toByteArray().length;

        if (size <= 102400) {
            return new RestMethod(null, true);
        } else {
            return new RestMethod(null, false);
        }
      } else {
        throw new ApplicationException(ErrorCategory.UNSPECIFIED, "noFile");
      }
    } catch (Exception e) {
      if (e instanceof ApplicationException) {
        ApplicationException applicationException = (ApplicationException) e;
        return new RestMethod(applicationException.getErrorMessage(), false);
      } else {
        return new RestMethod(e.getMessage(), false);
      }
    }
  }

实际大小为760KB,即77820字节,但它返回3475.为什么没有大小返回正确的图像大小?如何获得图像的实际尺寸?

1 个答案:

答案 0 :(得分:1)

最有可能的是文件问题,或者某种程度上您正在读错文件,或者在读取文件的代码(或过程)中存在一些问题。

您尝试使用其他图像文件吗?尝试使用操作系统通常提供的示例图像文件。那些通常会有正确的编码和元数据。

代码中获取图像大小的部分是正确的。我复制了那部分并将其放在桌面java程序中,我得到了正确的文件大小。

您在以下桌面java程序中为我工作的代码。

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class SimpleConvertImage2 {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        /*
         * 1. How to convert an image file to  byte array?
         */

        File file = new File("C:\\rose.jpg");

        FileInputStream fis = new FileInputStream(file);
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //InputStream is = url.openStream();
        byte[] b = new byte[2^16];
        int read = fis.read(b);

        while (read > -1) {
            baos.write(b, 0, read);
            read = fis.read(b);
        }

        int size = baos.toByteArray().length;

        System.out.println("image size original code : " + size);


    }
}

这是一个示例程序,我在处理读取和写入图像文件的图像时用作参考。这对你也有帮助。

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class SimpleConvertImage {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        /*
         * 1. How to convert an image file to  byte array?
         */

        File file = new File("C:\\rose.jpg");

        FileInputStream fis = new FileInputStream(file);
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Writes to this byte array output stream
                bos.write(buf, 0, readNum); 
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }

        byte[] bytes = bos.toByteArray();

        int size = bytes.length;

        System.out.println("image size : " + size);

        /*
         * 2. How to convert byte array back to an image file?
         */

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");

        //ImageIO is a class containing static methods for locating ImageReaders
        //and ImageWriters, and performing simple encoding and decoding. 

        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; 
        ImageInputStream iis = ImageIO.createImageInputStream(source); 
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();

        Image image = reader.read(0, param);
        //got an image file

        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        //bufferedImage is the RenderedImage to be written

        Graphics2D g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);

        File imageFile = new File("C:\\newrose2.jpg");
        ImageIO.write(bufferedImage, "jpg", imageFile);

        System.out.println(imageFile.getPath());
    }
}