How to convert BufferedImage RGBA to BufferedImage RGB? - java

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

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

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!

Converting BMP Type

I tried to convert a bmp:
File file = new File(source.getText());
try {
BufferedImage i = ImageIO.read(file);
if (i != null) {
BufferedImage convertedImg = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
boolean drawImage = convertedImg.getGraphics().drawImage(i, 0, 0, null);
File f = new File(output.getText().concat(File.separatorChar + "out.bmp"));
boolean write = ImageIO.write(convertedImg, "BMP", f);
} else {
//...
}
}catch (Exception e) {
e.printStackTrace();
}
But it doesn't write the image correctly. As I open the bmp it says the file is empty?? What am I doing wrong?
Edit: write returns false.

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