Как получить высоту изображения и ширину с помощью Java?

Неправильно указан путь к файлу. После того, как я попытался с внешней mp3-песней, она работала правильно.

this.wavesurfer.load("http://localhost:3000/public/song.mp3");
98
задан silver est 19 June 2016 в 08:57
поделиться

3 ответа

Попытайтесь использовать ImageInfo класс в свободном доступе, я использовал его для той же цели:

http://linux.softpedia.com/get/Multimedia/Graphics/ImageInfo-19792.shtml

4
ответ дан karim79 3 July 2019 в 07:39
поделиться

Можно загрузить jpeg двоичные данные как файл и проанализировать jpeg заголовки сами. Тот, который Вы ищете, является 0xFFC0, или Запустите Заголовка кадра:

Start of frame marker (FFC0)

* the first two bytes, the length, after the marker indicate the number of bytes, including the two length bytes, that this header contains
* P -- one byte: sample precision in bits (usually 8, for baseline JPEG)
* Y -- two bytes
* X -- two bytes
* Nf -- one byte: the number of components in the image
      o 3 for color baseline JPEG images
      o 1 for grayscale baseline JPEG images

* Nf times:
      o Component ID -- one byte
      o H and V sampling factors -- one byte: H is first four bits and V is second four bits
      o Quantization table number-- one byte

The H and V sampling factors dictate the final size of the component they are associated with. For instance, the color space defaults to YCbCr and the H and V sampling factors for each component, Y, Cb, and Cr, default to 2, 1, and 1, respectively (2 for both H and V of the Y component, etc.) in the Jpeg-6a library by the Independent Jpeg Group. While this does mean that the Y component will be twice the size of the other two components--giving it a higher resolution, the lower resolution components are quartered in size during compression in order to achieve this difference. Thus, the Cb and Cr components must be quadrupled in size during decompression.

Поскольку больше информации о заголовках проверяет jpeg запись Википедии, или я получил вышеупомянутую информацию здесь.

Я использовал метод, подобный коду, ниже которого я добрался из этого сообщения на форумах солнца:

import java.awt.Dimension;
import java.io.*;

public class JPEGDim {

public static Dimension getJPEGDimension(File f) throws IOException {
    FileInputStream fis = new FileInputStream(f);

    // check for SOI marker
    if (fis.read() != 255 || fis.read() != 216)
        throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");

    Dimension d = null;

    while (fis.read() == 255) {
        int marker = fis.read();
        int len = fis.read() << 8 | fis.read();

        if (marker == 192) {
            fis.skip(1);

            int height = fis.read() << 8 | fis.read();
            int width = fis.read() << 8 | fis.read();

            d = new Dimension(width, height);
            break;
        }

        fis.skip(len - 2);
    }

    fis.close();

    return d;
}

public static void main(String[] args) throws IOException {
    System.out.println(getJPEGDimension(new File(args[0])));
}

}

14
ответ дан joinJpegs 24 November 2019 в 05:06
поделиться

Я нашел другой способ чтения размера изображения (более общий). Вы можете использовать класс ImageIO совместно с ImageReaders. Вот пример кода:

private Dimension getImageDim(final String path) {
    Dimension result = null;
    String suffix = this.getFileSuffix(path);
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try {
            ImageInputStream stream = new FileImageInputStream(new File(path));
            reader.setInput(stream);
            int width = reader.getWidth(reader.getMinIndex());
            int height = reader.getHeight(reader.getMinIndex());
            result = new Dimension(width, height);
        } catch (IOException e) {
            log(e.getMessage());
        } finally {
            reader.dispose();
        }
    } else {
        log("No reader found for given format: " + suffix));
    }
    return result;
}

Обратите внимание, что getFileSuffix - это метод, который возвращает расширение пути без "." например: png, jpg и т. д. Пример реализации:

private String getFileSuffix(final String path) {
    String result = null;
    if (path != null) {
        result = "";
        if (path.lastIndexOf('.') != -1) {
            result = path.substring(path.lastIndexOf('.'));
            if (result.startsWith(".")) {
                result = result.substring(1);
            }
        }
    }
    return result;
}

Это очень быстрое решение, поскольку из файла считывается только размер изображения, а не все изображение. Я тестировал его, и нет никакого сравнения с производительностью ImageIO.read. Надеюсь, кому-то это пригодится.

48
ответ дан 24 November 2019 в 05:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: