Java ImageIO work on W10 but not W8 - java

So I wrote this program to read an image and change some of it's colors:
public class MorphImage {
private final String URL = "pic1.jpg";
public static void main(String[] args) {
try {
new MorphImage();
} catch (IOException e) {
e.printStackTrace();
}
}
public MorphImage() throws IOException {
BufferedImage image = readImage(URL);
pointOp(image, 50, 75);
}
/**
* Read and create a bufferedImage from an URL.
*
* #param URL
* #return
*/
private BufferedImage readImage(String URL) {
URL url = getClass().getResource(URL);
File file = new File(url.getPath());
BufferedImage bimg = null;
try {
bimg = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
return bimg;
}
/**
* Uses a BufferedImage to create a new copy of it with altered values.
*
* #param img
* #throws IOException
*/
private void pointOp(BufferedImage img, int con, int brig) throws IOException {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster inraster = img.getRaster();
WritableRaster outraster = image.getRaster();
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
int value = inraster.getSample(i, j, 0);
outraster.setSample(i, j, 0, 255 - value);
}
ImageIO.write(image, "PNG", new File("Morphed " + URL));
System.out.println("Morphed");
}
}
It work great on my laptop running Windows 10, but when I cloned the repo unto my pc running Windows 8.1, it can't find the the image "pic1.jpg" anymore. It throws IIOException Can't read input file. Both computers are running identical setups of JDK and Eclipse. I got all my files in the same package:
imager
-src
-main
-MorphImage.java
-pic1.jpg
Do anyone know what's wrong here?

Related

How to add several barcode images to one image png? [duplicate]

This question already has answers here:
How to combine multiple PNGs into one big PNG file?
(10 answers)
Closed 2 years ago.
My case is what I need to add several barcodes (png) which I generated using Barcode4j library in one png file. I couldn't find any examples, also couldn't make up my mind to solve it. So any help will be appreciated.
Well, I generate barcodes in usual way (throug for) and collecte them in a list of bufferedImages (List). Now I need to glue this images in one.
My code:
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
List<BufferedImage> bufferedImageList = new ArrayList<>(); // list for bufferedImages
for (int i = 0; i < barcodesList.size(); i++) {
try {
Code128Bean code128 = new Code128Bean();
code128.setHeight(15f);
code128.setModuleWidth(0.3);
code128.setQuietZone(10);
code128.doQuietZone(true);
code128.generateBarcode(canvas, (String) barcodesList.get(i));
bufferedImageList.add(canvas.getBufferedImage()); // collect images of barcode in cicle
canvas.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
FileOutputStream fos = new FileOutputStream(barcodePath.toString());
// to do smth to make one png from collected images
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Well, my code which combine several barcodes looks like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
List<BufferedImage> bufferedImageList = new ArrayList<>(); // list for bufferedImages
int sumHeight = 0;
int sumWhide = 0;
int columns = 2;
int rows = 0;
for (int i = 0; i < barcodesList.size(); i++) {
try {
Code128Bean code128 = new Code128Bean();
code128.setHeight(15f);
code128.setModuleWidth(0.3);
code128.setQuietZone(10);
code128.doQuietZone(true);
code128.generateBarcode(canvas, (String) barcodesList.get(i));
sumHeight = sumHeight + canvas.getBufferedImage().getHeight();
sumWhide = sumWhide + canvas.getBufferedImage().getWidth();
bufferedImageList.add(canvas.getBufferedImage()); // collect images of barcode in cycle
canvas.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
double dbl = barcodesList.size() / (double) columns;
rows = (int)Math.ceil(dbl);
int oneWhide = sumWhide / barcodesList.size();
int imgWhide = oneWhide * columns;
int oneHeight = sumHeight / barcodesList.size();
int imgHeight = oneHeight * rows;
BufferedImage bigImage = new BufferedImage(imgWhide, imgHeight, BufferedImage.TYPE_BYTE_BINARY);
Graphics g = bigImage.getGraphics();
int x = 0;
int y = 0;
for (BufferedImage bufferedImage : bufferedImageList) {
g.drawImage(bufferedImage, x, y, null);
x += oneWhide;
if(x >= bigImage.getWidth()){
x = 0;
y += bufferedImage.getHeight();
}
}
ImageIO.write(bigImage,"png",new File(barcodePath.toString()));
} catch (Exception e) {
e.printStackTrace();
}
}

Only half image while converting pdf to image using pdfbox

I am using pdfbox for converting a pdf to image but I am getting only half image of the original . Can somebody please help
String sourceDir = "D:/pdffiles/Sample_93.pdf"; // Pdf files are read from this folder
String destinationDir = "D:/images/png/"; // converted images from pdf document are saved here
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder Created -> "+ destinationFile.getAbsolutePath());
}
if (sourceFile.exists()) {
PDDocument document = PDDocument.loadNonSeq(new File(sourceDir), null);
List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
int page = 0;
for (PDPage pdPage : pdPages){
++page;
BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIOUtil.writeImage(bim, "Report" + "-" + page + ".png", 300);
}
document.close();
}
Below was the half image
incomplete image
Edit 1 :
1st page with content came out correctly the 2nd page with the images(its scanned as pdf images) came out only half .
Edit 2
Tried with the below code where the image got turned black areas to white and white areas to black
Total Black Image
public class ImageMain {
public static void setup() throws IOException {
// load a pdf from a byte buffer
File file = new File("D:/odimages/selection.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int numPgs = pdffile.getNumPages();
for (int i = 0; i < numPgs; i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
// save it as a file
BufferedImage bImg = toBufferedImage(img);
File yourImageFile = new File("D:/odimages/png/page_" + i + ".png");
ImageIO.write(bImg, "png", yourImageFile);
}
}
// This method returns a buffered image with the contents of an image
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent
// Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the
// screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
public static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage) image;
return bimage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
// Get the image's color model
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ImageMain.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}

How to write a grayscale image from a 2D array

I wanted to read a grayscale image values into a 2d array, change the values of the 2d array and create a new grayscale image from the modified values of 2d array.
Following is the code to read the grayscale image into 2D array(arr[][]).
package dct;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.io.File;
import javax.imageio.ImageIO;
/**
*
* #author jain
*/
public class writeGR {
public static void main(String[] args)
{
File file = new File("lightning.jpg");
BufferedImage img = null;
try
{
img = ImageIO.read(file);
}
catch(Exception e)
{
e.printStackTrace();
}
int width = img.getWidth();
int height = img.getHeight();
int[][] arr = new int[width][height];
Raster raster = img.getData();
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
arr[i][j] = raster.getSample(i, j, 0);
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
image.setData(raster);
//
//BufferedImage image1 = image;
try
{
File ouptut = new File("grayscale.png");
ImageIO.write(image, "png", ouptut);
}
catch(Exception e)
{
e.printStackTrace();
}
}// main
}
Now I want to change the "arr[][]" vlaues and create a new grayscale image out of that. How to do this?
The above problem can be solved by the following code:
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
tempArr[0] = 100;
raster1.setPixel(i, j, tempArr);
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
image.setData(raster1);
try
{
File ouptut = new File("change.png");
ImageIO.write(image, "png", ouptut);
}
catch(Exception e)
{
e.printStackTrace();
}

losing transparency when using imageinputstream and bufferedimage to create png strip from gif animation

I was finally able to write the following code which takes a animated GIF and converts it to a png strip. however for some reason it loses the transparency from the original gif. Can someone advise how i can keep the transparency
public class Main {
public static void main(String[] args) throws IOException {
Object input = new File("C:\\Users\\drizzt\\Documents\\jax.gif");
// or Object input = new FileInputStream("animated.gif");
ImageInputStream stream = ImageIO.createImageInputStream(input);
Iterator readers = ImageIO.getImageReaders(stream);
if (!readers.hasNext())
throw new RuntimeException("no image reader found");
ImageReader reader = (ImageReader) readers.next();
reader.setInput(stream); // don't omit this line!
int n = reader.getNumImages(true); // don't use false!
int h = reader.getHeight(0);
int w = reader.getWidth(0);
BufferedImage img = new BufferedImage(w * n, h,
BufferedImage.TYPE_INT_RGB);
boolean[] imagedrawn;
imagedrawn = new boolean[n];
// big.drawImage(outputimage, w*i, 0, null);
System.out.println("numImages = " + n);
for (int i = 0; i < n; i++) {
BufferedImage image = reader.read(i);
System.out.println("image[" + i + "] = " + image);
// img = BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
// img.createGraphics()
imagedrawn[i] = img.createGraphics().drawImage(image, w * i, 0,
null);
}
try {
// retrieve image
// BufferedImage bi = getMyImage();
File outputfile = new File("c:\\saved.png");
ImageIO.write(img, "png", outputfile);
} catch (IOException e) {
}
stream.close();
}
}
Replace this:
BufferedImage img = new BufferedImage(w * n, h, BufferedImage.TYPE_INT_RGB);
with
BufferedImage img = new BufferedImage(w * n, h, BufferedImage.TYPE_INT_ARGB);
...and you'll have transparency.
Possibly better yet, is to do:
BufferedImage img = reader.getRawImageType(0).createBufferedImage(w * n, h);
Then you'll keep the exact image layout from the GIF, and possibly get a smaller output image (a minor detail here, is that getRawImageType may return null if there's no corresponding color space in Java, but this should probably never happen for a GIF).
Unrelated to the issue, but still good practice: Whenever you do img.createGraphics() you should also call dispose() on the Graphics2D when done painting. Move the createGraphics() outside the loop and dispose after the loop for better performance.
It's even possible to avoid the drawing altogether, and read the contents of each frame directly into img, by replacing your loop with something like this:
ImageReadParam param = reader.getDefaultReadParam();
param.setDestination(img);
for (int i = 0; i++; i < n) {
param.setDestinationOffset(new Point(w * i, 0);
reader.read(i, param);
}

problem with saving image i get Zero kb

I'm having a problem, when I save my image I can't open it because it's empty and the size is zero kb. I'm reading the image from a folder and then I change the size to 100x100 and save it but it's not working. Here's the code I've written so far:
public BufferedImage resizeImageToPreview() {
final String SOURCE ="/Library/glassfishv3/glassfishv3/glassfish/domains/domain1/eclipseApps/LaFamilyEar/LaFamily_war/temp";
File source = new File(SOURCE);
BufferedImage image = null;
//Read images and convert them to BufferedImages
for (File img : source.listFiles()) {
try {
image = ImageIO.read(img);
} catch (IOException e) {
e.printStackTrace();
}
//Get image width and height
int w = image.getWidth();
int h = image.getHeight();
//Change the width and height to the image to 100x100
// BufferedImage dimg = new BufferedImage(100, 100, image.getType());
//Create graphics to be able to paint or change your image
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, 100, 100, 0, 0, w, h, null);
g.dispose();
String extension = ".jpg";
File dest = new File("/Users/ernestodelgado/Kurs_Java/EjbWorkspace/LaFamily/WebContent/small/"+img.getName());
try {
ImageIO.write(image, extension, dest);
} catch (IOException e) {
e.printStackTrace();
}
}
return image;
}
Try changing ..
String extension = ".jpg";
..to..
String extension = "jpg";
Obviously, add a "." to the file name at the relevant point.
If that does not work for you, try posting an SSCCE.
Try this example:
public class MakeSmaller {
public static void main(String... args) throws MalformedURLException,
IOException {
String url = "http://actionstalk.com/wp-content/uploads/2007/11/google_logo_3600x1500.jpg";
BufferedImage orig = ImageIO.read(new URL(url));
BufferedImage scaled = new BufferedImage(50, 50, orig.getType());
Graphics2D g = (Graphics2D) scaled.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(orig, 0, 0, scaled.getWidth(), scaled.getHeight(), null);
g.dispose();
ImageIO.write(scaled, "jpg", new File("test.jpg"));
}
}

Categories