Only half image while converting pdf to image using pdfbox - java

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

Related

How to soleve 'java.io.EOFException: Unexpected end of ZLIB input stream' while use ImageIO.read()

the png
I can open the png but used code to read it failed. The exception is
'java.io.EOFException: Unexpected end of ZLIB input stream' and the line is 4 where use ImageIO.read() function.
I succeded reading other png by using the same code.
public static void cut(String srcImageFile, String result, int x, int y, int width, int height) {
try {
// 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 源图宽度
int srcHeight = bi.getWidth(); // 源图高度
if (srcWidth > 0 && srcHeight > 0) {
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
Image img = Toolkit.getDefaultToolkit()
.createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "PNG", new File(result));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please tell me how to solve the problem.
If you open the image in Chrome or other tool, you will see that the lower part of the image (part of the QR code) is missing, or just black. This is because the PNG file is indeed corrupted, or rather truncated it seems. There is no way to "solve" this, other than getting a new copy of the file, without the truncation.
However, it is possible to partially read the PNG file using Java, just like in other tools. It just can't be done using ImageIO.read(...) convenience methods, because you will get an exception and no return value.
Instead, use the full verbose code:
BufferedImage image;
try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
ImageReader reader = ImageIO.getImageReaders(input).next(); // TODO: Handle no reader case
try {
reader.setInput(input);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
// Allocate an image to be used as destination
ImageTypeSpecifier imageType = reader.getImageTypes(0).next();
image = imageType.createBufferedImage(width, height);
ImageReadParam param = reader.getDefaultReadParam();
param.setDestination(image);
try {
reader.read(0, param); // Read as much as possible into image
}
catch (IOException e) {
e.printStackTrace(); // TODO: Handle
}
}
finally {
reader.dispose();
}
}
// image should now contain the parts of the image that could be read

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

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

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

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