problem with saving image i get Zero kb - java

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"));
}
}

Related

How to change the perspective of an image

Actually I am working on a application where I need to change the flooring of a room. The application's back end is in java.Suppose this is the room.
Room whose floor needs to be changed
Room after floor removed
Carpet which needs to be laid
Result after executing the code
I have removed the floor of the room using software like photoshop. Now I need to add new carpet floor to that image. The carpet flooring must be dynamic where a user selects any carpet and the images replaces after rendering.
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class FloorChange {
public static void main(String[] args) {
int width = 1920; // width of the image
int height = 1080; // height of the image
// For storing image in RAM
BufferedImage image = null;
BufferedImage background = null;
BufferedImage finalImage = null;
// READ IMAGE
try {
File input_file = new File("room.png"); // image file path
File floor_tile = new File("milkyway.jpg"); // image file path
FloorChange floorChange = new FloorChange();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
background = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
try {
Graphics2D g = finalImage.createGraphics();
g.drawImage(background, 0, 0, null);
g.drawImage(image, 0, 0, null);
File output_file = new File("floor1.png");
ImageIO.write(finalImage, "png", output_file);
System.out.println("Writing complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
private BufferedImage resizeImage(BufferedImage originalImage, int type) {
int IMG_WIDTH = 1920;
int IMG_CLAHEIGHT = 1080;
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_CLAHEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_CLAHEIGHT, null);
g.dispose();
return resizedImage;
}
I have replaced the floor but the image was stretched and if I repeat the image it gives lines between each carpet. And also the perspective of the imag e is not proper.

How to convert BufferedImage RGBA to BufferedImage RGB?

So I tried looking for the solution but could not find a solution where I can convert the RGBA to RGB format.
If a simple solution from BufferedImage to BufferedImage conversion is given then that will be best, otherwise the problem is as follows :
Basically I have to convert BufferedImage into MAT format. It works properly for JPG/JPEG images but not PNGs. Following code I use for the conversion ::
BufferedImage biImg = ImageIO.read(new File(imgSource));
mat = new Mat(biImg.getHeight(), biImg.getWidth(),CvType.CV_8UC3);
Imgproc.cvtColor(mat,matBGR, Imgproc.COLOR_RGBA2BGR);
byte[] data = ((DataBufferByte) biImg.getRaster().getDataBuffer()).getData();
matBGR.put(0, 0, data);
This throws error for images with RGBA values. So thus looking for a solution.
Thanks in advance.
I found a solution like this :
BufferedImage oldRGBA= null;
try {
oldRGBA= ImageIO.read(new URL("http://yusufcakmak.com/wp-content/uploads/2015/01/java_ee.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final int width = 1200;
final int height = 800;
BufferedImage newRGB = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
newRGB .createGraphics().drawImage(oldRGBA, 0, 0, width, height, null);
try {
ImageIO.write(newRGB , "PNG", new File("your path"));
} catch (IOException e) {}
So here when we creating new BufferedImage we can change type of the image with :
The RGB worked for me with PNG.
public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
if (original.getType() == type) {
return original;
}
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
}
finally {
g.dispose();
}
return image;
}

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 create an image from an InputStream, resize it and save it?

I have this code where i get an InputStream and create an image:
Part file;
// more code
try {
InputStream is = file.getInputStream();
File f = new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg");
OutputStream os = new FileOutputStream(f);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
} catch (IOException e) {
System.out.println("Error");
}
The problem is that I have to resize that image before i create if from the InputStream
So how to resize what I get from the InputStream and then create that resized image. I want to set the largest side of the image to 180px and resize the other side with that proportion.
Example:
Image = 289px * 206px
Resized image = 180px* 128px
I did this:
try {
InputStream is = file.getInputStream();
Image image = ImageIO.read(is);
BufferedImage bi = this.createResizedCopy(image, 180, 180, true);
ImageIO.write(bi, "jpg", new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg"));
} catch (IOException e) {
System.out.println("Error");
}
BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
And I did not use the other code.
Hope helps someone!

How to remove unnecessary black background after resizing the image to a fixed resolution?

I have been resizing every image to a fix resolution before adding it to my database .
for this purpose i have been using FileUpload and following code:-
logo_name = System.currentTimeMillis() + ".png";
File uploadedFile = new File("/www/static.appcanvas.com/"+logo_name);
BufferedImage bi = ImageIO.read(item.getInputStream());
Image img = bi.getScaledInstance(125,125,Image.SCALE_SMOOTH);
BufferedImage img_logo = new BufferedImage(125,125,BufferedImage.TYPE_INT_RGB);
Graphics2D g = img_logo.createGraphics();
g.drawImage(img,0,0,null);
if(g != null) g.dispose();
ImageIO.write(img_logo,"png",uploadedFile)
I get the image of the desired resolution but there is a unnecessary black background which i am unable to remove.
image before : http://www.rocketcampus.com/images/test.png
image after : http://static.appcanvas.com/1334085929080.png
You can change the type of your BufferedImage to BufferedImage.TYPE_INT_ARGB to have a transparent background.
This worked for me:
public static void main(String[] args) throws IOException {
FileInputStream item = new FileInputStream("D:/tmp/OpenFlexo_07.gif");
String logo_name = System.currentTimeMillis() + ".png";
File uploadedFile = new File("d:/www/static.appcanvas.com/" + logo_name);
BufferedImage bi = ImageIO.read(item);
Image img = bi.getScaledInstance(125, 125, Image.SCALE_SMOOTH);
BufferedImage img_logo = new BufferedImage(125, 125, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img_logo.createGraphics();
g.drawImage(img, 0, 0, null);
if (g != null) {
g.dispose();
}
uploadedFile.getParentFile().mkdirs();
uploadedFile.createNewFile();
ImageIO.write(img_logo, "png", uploadedFile);
}

Categories