Images
Learning IO and image manipulation.
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
public class ImageIOTest {
public static void main( String[] args ){
BufferedImage img = null; // buffer type
try {
// Name of file and directories
String name = "lambo";
String in = "images/";
String out = "images/tmp/";
// Either use URL or File for reading image using ImageIO
File imageFile = new File(in + name + ".png");
img = ImageIO.read(imageFile); // set buffer of image data
// ImageIO Image write to gif in Java
// Documentation https://docs.oracle.com/javase/tutorial/2d/images/index.html
ImageIO.write(img, "gif", new File(out + name + ".gif") ); // write buffer to gif
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Success");
}
}
ImageIOTest.main(null);
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
public class Pics {
private final String inDir = "images/"; // location of images
private final String outDir = "images/tmp/"; // location of created files
private String inFile;
private String resizedFile;
private String asciiFile;
private String grayScaledFile;
private String ext; // extension of file
private long bytes;
private int width;
private int height;
// Constructor obtains attributes of picture
public Pics(String name, String ext) {
this.ext = ext;
this.inFile = this.inDir + name + "." + ext;
this.resizedFile = this.outDir + name + "." + ext;
this.asciiFile = this.outDir + name + ".txt";
this.setStats();
}
// An image contains metadata, namely size, width, and height
public void setStats() {
BufferedImage img;
try {
Path path = Paths.get(this.inFile);
this.bytes = Files.size(path);
img = ImageIO.read(new File(this.inFile));
this.width = img.getWidth();
this.height = img.getHeight();
} catch (IOException e) {
}
}
// Console print of data
public void printStats(String msg) {
System.out.println(msg + ": " + this.bytes + " " + this.width + "x" + this.height + " " + this.inFile);
}
// Convert scaled image into buffered image
public static BufferedImage convertToBufferedImage(Image img) {
// Create a buffered image with transparency
BufferedImage bi = new BufferedImage(
img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
// magic?
Graphics2D graphics2D = bi.createGraphics();
graphics2D.drawImage(img, 0, 0, null);
graphics2D.dispose();
return bi;
}
// Scale or reduce to "scale" percentage provided
public void resize(int scale) {
BufferedImage img = null;
Image resizedImg = null;
int width = (int) (this.width * (scale/100.0) + 0.5);
int height = (int) (this.height * (scale/100.0) + 0.5);
try {
// read an image to BufferedImage for processing
img = ImageIO.read(new File(this.inFile)); // set buffer of image data
// create a new BufferedImage for drawing
resizedImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
} catch (IOException e) {
return;
}
try {
ImageIO.write(convertToBufferedImage(resizedImg), this.ext, new File(resizedFile));
} catch (IOException e) {
return;
}
this.inFile = this.resizedFile; // use scaled file vs original file in Class
this.setStats();
}
// convert every pixel to an ascii character (ratio does not seem correct)
public void convertToAscii() {
BufferedImage img = null;
PrintWriter asciiPrt = null;
FileWriter asciiWrt = null;
try {
File file = new File(this.asciiFile);
Files.deleteIfExists(file.toPath());
} catch (IOException e) {
System.out.println("Delete File error: " + e);
}
try {
asciiPrt = new PrintWriter(asciiWrt = new FileWriter(this.asciiFile, true));
} catch (IOException e) {
System.out.println("ASCII out file create error: " + e);
}
try {
img = ImageIO.read(new File(this.inFile));
} catch (IOException e) {
}
double pixVal = 0;
// Changing to go by blocks 2 times as tall as wide
// Height is in outer loop, so for each height the entire width is covered
// To get 2 times as tall as wide blocks, we can use 1 width x 2 height
// This is done by accounting for each pixel and the one below it in the inner for loop, then averaging
// To account for this in the outer for loop, we simply increment i by 2 to not overcount
// Also change the upper limit so that there is no error (since we will acount for i+1 within the code block)
for (int i = 0; i < img.getHeight() - 1; i+=2) {
for (int j = 0; j < img.getWidth(); j++) {
int pixel = img.getRGB(j, i);
Color col = new Color(pixel, true);
int pixel2 = img.getRGB(j, i+1);
Color col2 = new Color(pixel2, true);
pixVal = (col.getRed() + col2.getRed() + col.getBlue() + col2.getBlue() + col.getGreen() + col2.getGreen())/6;
try {
asciiPrt.print(asciiChar(pixVal));
asciiPrt.flush();
asciiWrt.flush();
} catch (Exception ex) {
}
}
try {
asciiPrt.println("");
asciiPrt.flush();
asciiWrt.flush();
} catch (Exception ex) {
}
}
}
// Gray scale method
public void GrayScale() {
BufferedImage img = null;
// Reading file
try {
img = ImageIO.read(new File(this.inFile));
} catch (IOException e) {
}
// Iterating through all pixels
for (int i = 0; i<this.height; i++) {
for (int j = 0; j<this.width; j++) {
// For each pixel, getting RGB contents
int pixel = img.getRGB(j, i);
// Creating color object out of RGB contents for easy extraction
Color color = new Color(pixel, true);
// Using color object's methods to get the R, G, and B values for the pixel
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Averaging R, G, and B
int avg = (red+green+blue)/3;
// Creating a new color object which has R=G=B=average
// This is because the average will be a shade of gray
Color colorGray = new Color(avg, avg, avg);
// Setting the pixel's actual RGB content in the image to be the grayscaled version.
img.setRGB(j, i, colorGray.getRGB());
}
}
// Writing the image out
try{
ImageIO.write(img, "png", new File("images/tmp/" + "grayLambo" + ".png") );
}catch(IOException e){
System.out.println(e);
}
}
// Red scale method
public void RedScale() {
BufferedImage img = null;
// Reading file
try {
img = ImageIO.read(new File(this.inFile));
} catch (IOException e) {
}
// Iterating through all pixels
for (int i = 0; i<this.height; i++) {
for (int j = 0; j<this.width; j++) {
// For each pixel, getting RGB contents
int pixel = img.getRGB(j, i);
// Creating color object out of RGB contents for easy extraction
Color color = new Color(pixel, true);
// Using color object's methods to get the R, G, and B values for the pixel
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Getting an average red color
int redAvg = red/3;
// Creating a new color object which has G and B as average
// Red is scaled so that it accounts for variations in intensity
// Essentially making it gray and then adding red
Color colorRed = new Color(red, redAvg, redAvg);
// Setting the pixel's actual RGB content in the image to be the redscaled version.
img.setRGB(j, i, colorRed.getRGB());
}
}
// Writing the image out
try{
ImageIO.write(img, "png", new File("images/tmp/" + "redLambo" + ".png") );
}catch(IOException e){
System.out.println(e);
}
}
// Green scale method
public void GreenScale() {
BufferedImage img = null;
// Reading file
try {
img = ImageIO.read(new File(this.inFile));
} catch (IOException e) {
}
// Iterating through all pixels
for (int i = 0; i<this.height; i++) {
for (int j = 0; j<this.width; j++) {
// For each pixel, getting RGB contents
int pixel = img.getRGB(j, i);
// Creating color object out of RGB contents for easy extraction
Color color = new Color(pixel, true);
// Using color object's methods to get the R, G, and B values for the pixel
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Getting an average green color
int greenAvg = green/3;
// Creating a new color object which has R and B as average
// Green is scaled so that it accounts for variations in intensity
// Essentially making it gray and then adding green
Color colorGreen = new Color(greenAvg, green, greenAvg);
// Setting the pixel's actual RGB content in the image to be the greenscaled version.
img.setRGB(j, i, colorGreen.getRGB());
}
}
// Writing the image out
try{
ImageIO.write(img, "png", new File("images/tmp/" + "greenLambo" + ".png") );
}catch(IOException e){
System.out.println(e);
}
}
// Blue scale method
public void BlueScale() {
BufferedImage img = null;
// Reading file
try {
img = ImageIO.read(new File(this.inFile));
} catch (IOException e) {
}
// Iterating through all pixels
for (int i = 0; i<this.height; i++) {
for (int j = 0; j<this.width; j++) {
// For each pixel, getting RGB contents
int pixel = img.getRGB(j, i);
// Creating color object out of RGB contents for easy extraction
Color color = new Color(pixel, true);
// Using color object's methods to get the R, G, and B values for the pixel
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Getting an average Blue color
int blueAvg = blue/3;
// Creating a new color object which has R and G as average
// Blue is scaled so that it accounts for variations in intensity
// Essentially making it gray and then adding blue
Color colorBlue = new Color(blueAvg, blueAvg, blue);
// Setting the pixel's actual RGB content in the image to be the bluescaled version.
img.setRGB(j, i, colorBlue.getRGB());
}
}
// Writing the image out
try{
ImageIO.write(img, "png", new File("images/tmp/" + "blueLambo" + ".png") );
}catch(IOException e){
System.out.println(e);
}
}
// conversion table, there may be better out there ie https://www.billmongan.com/Ursinus-CS173-Fall2020/Labs/ASCIIArt
public String asciiChar(double g) {
String str = " ";
if (g >= 240) {
str = " ";
} else if (g >= 210) {
str = ".";
} else if (g >= 190) {
str = "*";
} else if (g >= 170) {
str = "+";
} else if (g >= 120) {
str = "^";
} else if (g >= 110) {
str = "&";
} else if (g >= 80) {
str = "8";
} else if (g >= 60) {
str = "#";
} else {
str = "@";
}
return str;
}
// tester/driver
public static void main(String[] args) throws IOException {
Pics lambo = new Pics("lambo", "png");
Pics amog = new Pics("amongus", "png");
amog.resize(33);
amog.convertToAscii();
lambo.GrayScale();
lambo.RedScale();
lambo.GreenScale();
lambo.BlueScale();
lambo.printStats("Original");
lambo.resize(33);
lambo.printStats("Scaled");
lambo.convertToAscii();
}
}
Pics.main(null);