Java Methods for Writing and Reading Image Files in BSQ Format
Java Methods for Writing and Reading Image Files
The following two methods handle the header file (.cabecera) of an image, which describes the image and points to its associated data file (.dat).
Method escribirArchivo
This method writes the header file for an Imagen object and then calls escribirBSQ to write the image data.
public static void escribirArchivo(String nombreArchivo, Imagen imagen) throws IOException {
File f = new File(nombreArchivo);
FileWriter fr = new FileWriter(f);
PrintWriter pr = new PrintWriter(fr);
String nombre = f.getName();
nombre = nombre.replace(".cabecera", ".dat");
pr.write(nombre + "\r\n");
pr.write(imagen.getFormatoImagen() + "\r\n");
pr.write(imagen.getNumeroBandas() + "\r\n");
pr.write("[");
for (int x = 0; x < imagen.getNumeroBandas(); x++) {
if (x == imagen.getNumeroBandas() - 1) {
pr.write(imagen.getBanda(x).toString() + "]\r\n");
} else {
pr.write(imagen.getBanda(x).toString() + ";");
}
}
pr.write(imagen.getLineas() + "\r\n");
pr.write(imagen.getColumnas() + "\r\n");
pr.close();
nombre = f.getParent() + File.separator + nombre;
escribirBSQ(nombre, imagen);
}Method leerArchivo
This method reads the header file, extracts the image properties and band names, and then calls leerBSQ to load the image data.
public static Imagen leerArchivo(String nombreArchivo) throws IOException {
File f = new File(nombreArchivo);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String nombreArchivoDatos = br.readLine();
String formatoImagen = br.readLine();
int numeroBandas = Integer.parseInt(br.readLine());
String nombreBandas = br.readLine();
String[] nombreBandasArray = nombreBandas.split(";");
nombreBandasArray[0] = nombreBandasArray[0].substring(1, nombreBandasArray[0].length());
nombreBandasArray[nombreBandasArray.length - 1] = nombreBandasArray[nombreBandasArray.length - 1].substring(0, nombreBandasArray[nombreBandasArray.length - 1].length() - 1);
int numLineas = Integer.parseInt(br.readLine());
int numColumnas = Integer.parseInt(br.readLine());
br.close();
nombreArchivoDatos = f.getParent() + File.separator + nombreArchivoDatos;
return leerBSQ(nombreArchivoDatos, new Imagen(numLineas, numColumnas, formatoImagen), nombreBandasArray);
}