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 )

- Rejestracja:ponad 17 lat
- Ostatnio:ponad 8 lat
- Postów:1105
0
Odczytaj sobie to z nagłówka.

- Rejestracja:ponad 17 lat
- Ostatnio:ponad 8 lat
- Postów:1105
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)
Zarejestruj się i dołącz do największej społeczności programistów w Polsce.
Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.