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

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.imageio.ImageIO;

/**
 *
 */
public class IO {

    public static void writeArrayToFile(String filename, byte arr[]) throws IOException {

        OutputStream fout = null;
        try {
            fout = new BufferedOutputStream(new FileOutputStream(filename, false));
            if (arr != null) {
                new PrintStream(fout).write(arr, 0, arr.length);
            }
            fout.flush();
        } finally {
            if (fout != null) {
                fout.close();
            }
        }
    }

    public static void writeStringToFile(String filename, String str) throws IOException {
        writeArrayToFile(filename, str.getBytes("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;
    }
}
