Android image format conversion

In the face recognition project, the first step is to register the face. At present, the program requires to save the image in JPG format in the specified folder to complete the face registration.

In use, some users don't have a deep understanding of the JPG format, mistakenly thinking that as long as the picture ending with ". JPEG" or ". JPG" is the JPG format, even some users deliberately change "Zhang San. png" to "Zhang San. JPG" to "gather" the jpg format picture to meet the requirements.

In fact, the file extension (. jpg) has nothing to do with the file. It's an extension that people impose for the convenience of distinguishing. Just like there is no extension for files in linux system.

So how to judge whether the image file is JPG? We need to understand the storage of image files. bmp, JPG and png image storage are quite different, but they are mainly divided into three parts: file header, color palette and data area;

We can judge the format of the file by the file header. Here is a tool class encapsulated according to this idea, which is mainly used for bmp, png conversion to JPG


/**
 * Title:
 * Description:
 * Company: Beijing xxxx Technology Co., Ltd., support@interjoy.com.cn
 *
 * @author Created by ylwang on 2018/1/24
 */


public class PicUtils {
    private static final String PNG = "png";
    private static final String JPG = "jpg";
    private static final String JPEG = "jpeg";
    private static final String BMP = "bmp";
    // private static final String[] imgSuffixes = {PNG, JPG, JPEG, BMP};
    private static final List<String> fileSuffixes = Arrays.asList(PNG, JPG, JPEG, BMP);
    // Cache file header information - file header information
    private static final ArrayMap<String, String> mFileTypes = new ArrayMap<String, String>();

    static {
        // images
        mFileTypes.put("FFD8FFE0", JPG);
        mFileTypes.put("89504E47", PNG);
        mFileTypes.put("424D5A52", BMP);
    }

    /**
     * Convert folder picture file to JPG
     *
     * @param dir Folder path of the picture
     */
    public static void ImgToJPG(File dir) {
        File[] files = dir.listFiles();
        String filePath = "";
        for (int i = 0; i < files.length; i++) {
            //First, filter the non image through the suffix
            String fileType = files[i].getName().substring(files[i].getName().lastIndexOf('.') + 1);
            if (fileSuffixes.contains(fileType.toLowerCase())) {
                filePath = files[i].getPath();
                String imgType = mFileTypes.get(getFileHeader(filePath)); //Get the real header
                if (!TextUtils.isEmpty(imgType) && !imgType.equals(JPG)) {
                    convertToJpg(filePath, filePath.substring(0, filePath.lastIndexOf('.') + 1) + JPG);
                }
            }
        }
    }

    /**
     * Convert to JPG format picture and delete the original picture
     *
     * @param pngFilePath png Or bmp photos
     * @param jpgFilePath jpg Photo
     */
    public static void convertToJpg(String pngFilePath, String jpgFilePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(pngFilePath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(jpgFilePath));
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)) {
                bos.flush();
            }
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bitmap.recycle();
            bitmap = null;
        }
        //Delete non JPG photos
        if (!pngFilePath.equals(jpgFilePath)) {
            File oldImg = new File(pngFilePath);
            oldImg.delete();
        }
    }


    /**
     * Get the file header information according to the file path
     *
     * @param filePath File path
     * @return File header information
     */
    public static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(filePath);
            byte[] b = new byte[4];
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return value;
    }

    /**
     * Convert the byte array of the file to read the header information to a string type representation
     *
     * @param src byte array of files to read header information
     * @return File header information
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return "";
        }
        for (int i = 0; i < src.length; i++) {
            // Returns a string representation of an integer parameter as a hexadecimal (Radix 16) unsigned integer and converts it to uppercase
            String hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
        return builder.toString();
    }
}



Tags: Linux

Posted on Sun, 03 May 2020 06:03:54 -0400 by Popcorn