All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.vfdtech.implementations.FileUtil Maven / Gradle / Ivy

Go to download

A utilities service with generic tools implementation. Can be plugged into your java project

There is a newer version: 0.3.5
Show newest version
package org.vfdtech.implementations;

import org.vfdtech.exceptions.CustomException;
import org.vfdtech.interfaces.IFileUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.imgscalr.Scalr;

public class FileUtil implements IFileUtil {

    List imageFormats = Arrays.asList("PNG", "JPG", "GIF", "JPEG");

    public String bufferedToBase64String(BufferedImage img, String formatName) throws UncheckedIOException {
        if (formatName == null || !imageFormats.contains(formatName.toUpperCase())) {
            throw new IllegalArgumentException("Format name (formatName) must be among " + imageFormats);
        }
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try (final OutputStream b64os = Base64.getEncoder().wrap(os)) {
            ImageIO.write(img, formatName, b64os);
        } catch (final IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
        return os.toString();
    }

    public File buildFileFromString(String img, String[] allowedMimeTypes) throws Exception {
        HashMap fileDetails = doFileValidation(
                img,
                allowedMimeTypes
        );
        String fileExtension = (String) fileDetails.get("fileExtension");

        Path file = Files.createTempFile(
                "NEW" + System.currentTimeMillis(),
                "." + fileExtension
        );
        byte[] fileBytes = (byte[]) fileDetails.get("fileBytes");

        FileUtils.writeByteArrayToFile(file.toFile(), fileBytes);
        return file.toFile();
    }

    public String compressImageString(String base64Img, String[] allowedMimeTypes) {
        return null;
    }

    public BufferedImage compressImage(String imageString, int targetWidth, int targetHeight) throws IOException {
        BufferedImage bufferedImage = new BufferedImage(
                targetWidth,
                targetHeight,
                BufferedImage.TYPE_INT_RGB
        );

        Path newFile = Files.createTempFile(
                "NEW" + System.currentTimeMillis(),
                "." + "jpg"
        );
        File writeToFile = newFile.toFile();
        FileUtils.writeByteArrayToFile(writeToFile, imageString.getBytes());

        ImageIO.write(bufferedImage, "jpg", writeToFile);

        return Scalr.resize(bufferedImage, targetWidth);
    }

    public HashMap doFileValidation(String img, String[] allowedMimeTypes) throws Exception {
        HashMap fileDetails;
        fileDetails = getFileAndFileExtension(img);
        if (fileDetails == null) {
            throw new CustomException("File can not be decoded");
        }
        String fileExtension = (String) fileDetails.get("fileExtension");
        if (!Arrays.asList(allowedMimeTypes).contains(fileExtension)) {
            throw new CustomException("File extension not supported. Consider " + Arrays.asList(allowedMimeTypes));
        }
        return fileDetails;
    }

    public HashMap getFileAndFileExtension(String base64ImageString) {
        try {
            HashMap fileDet = new HashMap<>();
            String delims = "[,]";
            String[] parts = base64ImageString.split(delims);
            String imageString = parts.length > 1 ? parts[1] : parts[0];
            byte[] imageByteArray = Base64.getDecoder().decode(imageString);

            InputStream is = new ByteArrayInputStream(imageByteArray);

            String fileExtension;
            String mimeType = URLConnection.guessContentTypeFromStream(is);
            mimeType = mimeType != null ? mimeType : "jpg";
            String delimiter = "[/]";
            String[] tokens = mimeType.split(delimiter);
            fileExtension = tokens.length > 1 ? tokens[1] : tokens[0];
            fileDet.put("fileExtension", fileExtension);
            fileDet.put("fileBytes", imageByteArray);
            return fileDet;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    public String convertFileToString(File file) {
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy