简体   繁体   English

如何在java中获取图像大小

[英]how to get image size in java

Application wants to check existing uploaded image, does it exceed maximum limit or not. 应用程序要检查现有的上传图片,它是否超过最大限制。

Here is the controller 这是控制器

@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);
      }
    }
  }

Actual size is 760KB which is 77820 Byte, but it returned 3475. Why didn't size return correct size of the image? 实际大小为760KB,即77820字节,但返回了3475。为什么大小没有返回正确的图像大小? How to get image actual size? 如何获得图像的实际尺寸?

Most probably it is a file issue or somehow you are reading a wrong file or there is some issue in code(or process) of reading the file. 最有可能是文件问题,或者您以某种方式读取了错误的文件,或者读取文件的代码(或过程)出现了问题。

Did your try with another image file ? 您是否尝试过其他图像文件? Try with sample image files that your OS usually provides. 尝试使用操作系统通常提供的示例图像文件。 Those usually will have correct encoding and meta data. 这些通常将具有正确的编码和元数据。

The part of your code which gets the size of image is correct. 您的获取图像大小的代码部分是正确的。 I copied that part and put it inside a desktop java program and i got the correct file size. 我复制了该部分并将其放入桌面Java程序中,然后得到了正确的文件大小。

Your code which worked for me in desktop java program below. 您的代码在下面的桌面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);


    }
}

Here is an example program which I use as a reference when dealing with images which reads and writes an image file. 这是一个示例程序,在处理读取和写入图像文件的图像时,我将用作参考程序。 This may help you as well. 这也可能对您有帮助。

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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM