/*
 * Copyright (c) 2014 Paul Scherrer Institute. All rights reserved.
 */
package ch.psi.plot.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.imageio.ImageIO;

/**
 *
 */
public class IO {

    public static void writeArrayToFile(String filename, byte[] arr) throws IOException {        
        Files.write(Paths.get(filename),arr);                
    }

    public static void writeStringToFile(String filename, String str) throws IOException {
        writeArrayToFile(filename, str.getBytes(StandardCharsets.UTF_8));
    }

    public static void writeImageToFile(BufferedImage image, String filename, String format) throws IOException {
        if (image != null) {
            ImageIO.write(image, format, new File(filename));
        }
    }
    
    public static BufferedImage readImageFromFile(String filename) throws IOException {
      return ImageIO.read(new File(filename));
    }

    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 && i < s.length() - 1) {
            ext = s.substring(i + 1).toLowerCase();
        }
        return ext;
    }
}
