1. Descripción del problema
Durante el desarrollo del proyecto, a menudo encontramos un problema de cargar archivos, que es el formato de la imagen para obtener. En muchos casos, muchas personas usan el nombre del sufijo para juzgar, como se muestra a continuación.
if (filename.endswith (". png") || filename.endswith (". jpg")) {// Guardar la imagen} else {tirar nueva IOException ("Formato de archivo de error!");}Sin embargo, este método no es confiable. Podemos intentar cargar el archivo ZIP, el archivo RMVB, el CSS, JS para modificar el nombre del sufijo JPG o PNG, o cargarlo en el servidor, lo que hace que aparezcan datos sucios en nuestro servidor. Además, para algunos archivos de imagen, si se modifican a la extensión incorrecta, es posible que algunos navegadores no puedan mostrar la imagen.
2. Solución
En los sistemas informáticos, los archivos de tipo de medios tienen [identificadores], y la cremallera y las imágenes mismas pertenecen a archivos multimedia, por lo que podemos determinar si las imágenes son legales mediante la codificación y decodificación.
1. Método para juzgar y marcar
ISBMP booleano estático privado (byte [] buf) {byte [] markbuf = "bm" .getBytes (); // Los dos primeros bytes del archivo de imagen BMP de retorno de retorno (BUF, MarkBuf); } ISicon booleano estático privado (byte [] buf) {byte [] markbuf = {0, 0, 1, 0, 1, 0, 32, 32}; Comparación de retorno (BUF, MarkBuf); } private static boolean iswebp (byte [] buf) {byte [] markbuf = "riff" .getBytes (); // WebP Image Identificador de retorno Compare (BUF, MarkBuf); } ISGIF booleano estático privado (byte [] buf) {byte [] markbuf = "gif89a" .getBytes (); // Identificador GIF if (compare (buf, markbuf)) {return true; } markbuf = "gif87a" .getBytes (); // Identificador GIF if (compare (buf, markbuf)) {return true; } return false; } ISPNG booleano estático privado (byte [] buf) {byte [] markbuf = {(byte) 0x89,0x50,0x4e, 0x47,0x0d, 0x0a, 0x1a, 0x0a}; // identificador png // nueva cadena (buf) .indexof ("png")> 0 // Este método también se puede usar para devolver compare (buf, markbuf); } private static boolean isJpegheader (byte [] buf) {byte [] markbuf = {(byte) 0xff, (byte) 0xd8}; // JPEG Start Caracter Devuelve Compare (BUF, MarkBuf); } private static boolean isjpegfooter (byte [] buf) // jpeg final final {byte [] markBuf = {(byte) 0xff, (byte) 0xd9}; Comparación de retorno (BUF, MarkBuf); }2. Métodos centrales
/ ** * Obtenga el MIMETYPE del archivo * @param FileName * @return */ private static string getMImetype (string filename) {try {string mImetype = readType (nombre de archivo); return String.Format ("Image/%s", mImetype); } catch (ioException e) {E.PrintStackTrace (); } return null; } / ** * Leer tipo de archivo * @param nombre de archivo * @return * @throws ioexception * / private static string readType (string filename) lanza ioexception {fileInputStream fis = null; intente {archivo f = nuevo archivo (nombre de archivo); if (! f.exists () || f.ISDirectory () || f.length () <8) {tire nueva ioException ("el archivo ["+f.getabsolutePath ()+"] ¡no es imagen!"); } fis = new FileInputStream (f); byte [] bufHeaders = readInputStreamat (Fis, 0,8); if (isJpegheader (bufheaders)) {long skiplength = f.length ()-2-8; // La primera vez que leí 8 bytes, por lo que necesito restar byte [] buffooters = readInputStreamat (FIS, Skiplength, 2); if (isJpegfooter (buffooters)) {return "jpeg"; }} if (ispng (bufheaders)) {return "png"; } if (isgif (bufheaders)) {return "gif"; } if (isWebp (bufHeaders)) {return "webp"; } if (isbmp (bufheaders)) {return "bmp"; } if (isicon (bufheaders)) {return "ico"; } tirar nueva IOException ("¡El formato de la imagen es desconocido!"); } catch (FileNotFoundException e) {Throw E; } finalmente {try {if (fis! = null) fis.close (); } capt (excepción e) {}}} / *** Comparación de consistencia de marca* @param buf mark para ser detectado* @param markbuf identificador byte array* @return return false mark no coincidir* / private static boolean compare (byte [] byte [] byte b) OR MarkBuf [i]; byte a = buf [i]; if (a! = b) {return false; }} return verdadero; } / **** @param FIS Input Stream Object* @param Skiplength Skip Longitud de posición* @param longitud longitud para leer* @return byte array* @throws ioexception* / private static byte [] readInputStreamat (fileInputStream fis, longitud larga, intent a longitud) lanza ioexception {byte [] buF = nuevo [longitud]; fis.skip (skiplength); // int read = fis.read (buf, 0, longitud); devolver buf; }3. Código de prueba
Prueba normal
public class ImageType {public static void main (string [] args) {String filename = "Oschina.jpg"; String type = getMimeType (nombre de archivo); System.out.println (tipo); }} Producción
Imagen/jpeg
Modificar la prueba de extensión
① Modificar Oschina.jpeg a Oschina.png
②Copy Oschina.png para eliminar la extensión
public class ImageType {public static void main (string [] args) {string filename = "oschina.png"; String type = getMimeType (nombre de archivo); System.out.println (tipo); FileName = "Oschina"; type = getMimeType (nombre de archivo); System.out.println (tipo); }} Producción
Imagen/jpeg
Imagen/jpeg
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.