Last active
October 10, 2017 10:56
-
-
Save AliZafar120/c2635ac916577cca8a65cde1894dbd8c to your computer and use it in GitHub Desktop.
Convert all images in a folder into grey scale image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color; | |
import java.awt.image.BufferedImage; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStreamWriter; | |
import java.io.RandomAccessFile; | |
import java.io.Writer; | |
import java.nio.channels.FileChannel; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.stream.Stream; | |
import javax.imageio.ImageIO; | |
public class TransformFiles { | |
public static void main(String[] args) throws IOException { | |
final File folder= new File("C:\\Users\\User\\Desktop\\Road and Cars\\Road_negatives"); | |
for (final File fileEntry : folder.listFiles()) { | |
BufferedImage img = null; | |
//read image | |
try{ | |
img = ImageIO.read(fileEntry); | |
}catch(IOException e){ | |
System.out.println(e); | |
} | |
//get image width and height | |
int width = img.getWidth(); | |
int height = img.getHeight(); | |
//convert to grayscale | |
for(int y = 0; y < height; y++){ | |
for(int x = 0; x < width; x++){ | |
int p = img.getRGB(x,y); | |
int a = (p>>24)&0xff; | |
int r = (p>>16)&0xff; | |
int g = (p>>8)&0xff; | |
int b = p&0xff; | |
//calculate average | |
int avg = (r+g+b)/3; | |
//replace RGB value with avg | |
p = (a<<24) | (avg<<16) | (avg<<8) | avg; | |
img.setRGB(x, y, p); | |
} | |
} | |
//write image | |
try{ | |
ImageIO.write(img, "jpg",new File("C:\\Users\\User\\Desktop\\Road and Cars\\negative\\"+fileEntry.getName())); | |
}catch(IOException e){ | |
System.out.println(e); | |
} | |
} | |
} | |
} | |
/* | |
* BufferedImage inputFile = null; | |
try { | |
inputFile = ImageIO.read(fileEntry); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
for (int x = 0; x < inputFile.getWidth(); x++) { | |
for (int y = 0; y < inputFile.getHeight(); y++) { | |
int rgba = inputFile.getRGB(x, y); | |
Color col = new Color(rgba, true); | |
col = new Color(255 - col.getRed(), | |
255 - col.getGreen(), | |
255 - col.getBlue()); | |
inputFile.setRGB(x, y, col.getRGB()); | |
} | |
} | |
try { | |
File outputFile = new File("C:\\Users\\User\\Desktop\\Road and Cars\\negative\\"+fileEntry.getName()); | |
ImageIO.write(inputFile, "jpg", outputFile); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment