Can I somehow insert an image by coordinates into another image?
A MultipartFile comes to me with an image, if its aspect ratio != 16:9, then I generate a new image with that aspect ratio and black and in the middle of it I need to insert the image that came to me.
At the moment I can only generate a black image, but I have no way to figure out how to insert the image by coordinates into another image.
I tried using Graphics2D.drawImage(), but it didn't work for me.
`public static String getImageAndReturnPathToResult(MultipartFile multipartFile){
try{
> //Image taken from the front
BufferedImage image = ImageIO.read(multipartFile.getInputStream());
> //Generating a new black image
BufferedImage bufferedImage = new BufferedImage(1920, 1080, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setColor(Color.black);
g2d.fillRect(0, 0, 1920, 1080);
g2d.dispose();
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}`
Most likely you failed with Graphics2D.drawImage() because you didn't pass the arguments correctly. Try:
Graphics2D.drawImage(image, x, y, null);
Graphics2D.dispose();
After that everything should work.
Related
I have been following some StackOverflow links using Graphics2D to change the background color of a BufferedImage.
The project I am working on requires that I read in a png image from a given url; the png image retrieved has a transparent background, and I would like to set it to white.
Here is what I have:
String u = this.format() ;
BufferedImage image = null ;
try{
URL url = new URL(u) ;
image = ImageIO.read(url) ;
Graphics2D graphics = image.createGraphics() ;
graphics.setBackground(Color.WHITE) ;
graphics.clearRect(0, 0, image.getWidth(), image.getHeight()) ;
ImageIO.write(image, "png", new File(outPath + fileName)) ;
graphics.dispose() ;
}
catch(IOException e){
e.printStackTrace() ;
}
The problem I am running into is that when I view the image, the image appears as a solid white box. Apparently I have overlaid a white background on top of the existing image that I retrieved.
How can I preserve the original image and only change the background? Or set the background first and then overlay the retrieved image?
1- Load your image
image = ImageIO.read(url) ;
2- Create a new BufferedImage of the same size
BufferedImage background = new BufferedImage(image.getWidth(), image.getHeight, BufferedImage.TYPE_INT_RGB);
3- Fill the background image with the desired color
Graphics2D g2d = background.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, background.getWidth(), background.getHeight());
4- Draw the original image onto the background...
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
background is now filled with the desired color and has the image painted on top o it.
I have a PNG image and I want to resize it. How can I do that? Though I have gone through this I can't understand the snippet.
If you have an java.awt.Image, resizing it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Obviously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT: Use the default image-scaling algorithm.
Image.SCALE_FAST: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
Image.SCALE_SMOOTH: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
Image.SCALE_AREA_AVERAGING: Use the Area Averaging image scaling algorithm.
Image.SCALE_REPLICATE: Use the image scaling algorithm embodied in the ReplicateScaleFilter class.
See the Javadoc for more info.
We're doing this to create thumbnails of images:
BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
tGraphics2D.setBackground( Color.WHITE );
tGraphics2D.setPaint( Color.WHITE );
tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled
ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file
Try this:
ImageIcon icon = new ImageIcon(UrlToPngFile);
Image scaleImage = icon.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT);
Resize image with high quality:
private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {
try {
BufferedImage image = ImageIO.read(uploadedInputStream);
Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, width, height, null);
g2d.dispose();
g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
// Something is going wrong while resizing image
return uploadedInputStream;
}
}
int newHeight = 150;
int newWidth = 150;
holder.iv_arrow.requestLayout();
holder.iv_arrow.getLayoutParams().height = newHeight;
holder.iv_arrow.getLayoutParams().width = newWidth;
holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
holder.iv_arrow.setImageResource(R.drawable.video_menu);
Simple way in Java
public void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
Design jLabel first:
JLabel label1 = new JLabel("");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setBounds(628, 28, 169, 125);
frame1.getContentPane().add(label1); //frame1 = "Jframe name"
Then you can code below code:
ImageIcon imageIcon1 = new ImageIcon(new ImageIcon("add location url").getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); //100, 100 add your own size
label1.setIcon(imageIcon1);
I'm reading a PNG image with the following code:
BufferedImage img = ImageIO.read(new URL(url));
Upon displaying it, there is a black background, which I know is caused from PNG transparency.
I found solutions to this problem suggesting the use of BufferedImage.TYPE_INT_RGB, however I am unsure how to apply this to my code above.
Create a second BufferedImage of type TYPE_INT_RGB...
BufferedImage copy = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
Paint the original to the copy...
Graphics2D g2d = copy.createGraphics();
g2d.setColor(Color.WHITE); // Or what ever fill color you want...
g2d.fillRect(0, 0, copy.getWidth(), copy.getHeight());
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
You now have a non transparent version of the image...
To save the image, take a look at Writing/Saving an Image
Currently, when I load an image off disk,
BufferedImage img = ImageIO.read(new File("myfile.png");
The resulting color space is one of ARGB. What I'd prefer is a plain old RGB, but without having to do the filtering myself.
Is there a way to open an image in a certain color mode?
I'm not aware of a way to open it with a specific color format, but you can create a new BufferedImage of the desired format and draw the old image on to it:
BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = img2.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
Any transparent parts in the original image will be drawn over a black background in the new image. If you'd prefer a different background, you can insert these lines before the drawImage call:
g.setColor(Color.white); // or whichever
g.fillRect(0, 0, img.getWidth(), img.getHeight());
I need to create .jpeg/.png file on my Android application programmatically. I have simple image (black background), and it need to write some text on it programmatically. How can I do it? Is it possible?
It's definately possible.
To write text on an image you have to load the image in to a Bitmap object. Then draw on that bitmap with the Canvas and Paint functions. When you're done drawing you simply output the Bitmap to a file.
If you're just using a black background, it's probably better for you to simply create a blank bitmap on a canvas, fill it black, draw text and then dump to a Bitmap.
I used this tutorial to learn the basics of the canvas and paint.
This is the code that you'll be looking for to turn the canvas in to an image file:
OutputStream os = null;
try {
File file = new File(dir, "image" + System.currentTimeMillis() + ".png");
os = new FileOutputStream(file);
finalBMP.compress(CompressFormat.PNG, 100, os);
finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
screenGrabFilePath = file.getPath();
} catch(IOException e) {
finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
Log.e("combineImages", "problem combining images", e);
}
Yes, see here
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
You can also use awt's Graphics2D with this compatibility project
Using Graphics2d you can create a PNG image as well:
public class Imagetest {
public static void main(String[] args) throws IOException {
File path = new File("image/base/path");
BufferedImage img = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.YELLOW);
g2d.drawLine(0, 0, 50, 50);
g2d.setColor(Color.BLACK);
g2d.drawLine(50, 50, 0, 100);
g2d.setColor(Color.RED);
g2d.drawLine(50, 50, 100, 0);
g2d.setColor(Color.GREEN);
g2d.drawLine(50, 50, 100, 100);
ImageIO.write(img, "PNG", new File(path, "1.png"));
}
}