Format obrazka

0

Jak w kodzie Javy pobrać format obrazka ? (zakładając, że rozszerzenie pliku jest nieprawidłowei że metoda ImageIO.read rzuca wyjątkiem dla podanego rozszerzenia )

0

Odczytaj sobie to z nagłówka.

0

Domyślam się :]. Jakie klasy ?

1

Odczytaj po prostu te kilka bajtów z pliku i tyle.

1

Na przyszłość podaje przykładowe algorytmy.

static final String HEXES = "0123456789ABCDEF";
    public static String getHex( byte [] raw ) {
        if ( raw == null ) {
          return null;
        }
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
        for ( final byte b : raw ) {
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
             .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
      }

public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

try {
	String[] images = {"img1", "img2"};
	for(String image : images){
		byte[] imb = GraphicsUtilities.getBytesFromFile(new File(filePath, image));
		if(getHex(imb).contains("FFD8FF")){
                    System.out.println("JPG");
                } else {
                    System.out.println("Not JPG");
                }
	}
} catch (IOException e) {
	e.printStackTrace();
}

Przykładowe sygnatury :

GIF-‚GIF89a‘ (0x474946383961); ‚GIF87a‘ (0x474946383761)
JPEG/JFIF-0xFFD8FF; ‚JFIF‘ (0x4A464946).
PNG-(0x89504e470d0a1a0a)

0

O właśnie ! Już to niby mam, zrobione moim pokrętnym sposobem, ale właśnie chciałem to zobaczyć w takiej wersji jaka jest przedstawiona na tym linku. Dzięki :).

0

A nie lepiej odczytać MIME z danego pliku? Np. przez

new MimetypesFileTypeMap().getContentType(file)

1 użytkowników online, w tym zalogowanych: 0, gości: 1