We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

[Java] - Draw a rectangle to an existing JPEG image

Hi,
Iā€™d like to draw a rectangle (X, Y, Width, Height) on a JPEG image to mask a part of the image.

I search for an example, but without success.

If anyone can help :slight_smile:

Thanks

Hi, @vfiot.
Welcome to our forum! Thank you for using Aspose.Imaging.
Please, take a look at this article https://docs.aspose.com/imaging/java/drawing-images-using-graphics/#drawing-images-using-graphics--complete-source

In your case you need only change the code

try (com.aspose.imaging.Image image = com.aspose.imaging.Image.create(createOptions, 500, 500))

by

try (com.aspose.imaging.Image image = com.aspose.imaging.Image.load("your_jpeg.jpg"))

and use Graphics.drawRectangle

I hope, it will help you.

Thanks for the answer.

Here is the code I have:

		//Create an instance of Image
		try (com.aspose.imaging.Image image = com.aspose.imaging.Image.load(inputFile))
		{
			//Create and initialize an instance of Graphics
			com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(image);

			//Clear the image surface with white color
			//graphics.clear(Color.getWhite());

			//Create and initialize a Pen object with blue color
			com.aspose.imaging.Pen pen = new com.aspose.imaging.Pen(com.aspose.imaging.Color.getBlue());
			
			RectangleF rec = new RectangleF();
			rec.setX(0);
			rec.setY(0);
			rec.setHeight(200);
			rec.setWidth(200);
			
			graphics.drawRectangle(pen, rec);

			// Save all changes.
			image.save();
		}

A rectangle is now created on the image, but I would like the backgroupd color of the rectangle to be black, not transparent.

Do you know how to do that ?

Thanks

@vfiot you can use example from https://docs.aspose.com/imaging/net/drawing-images/#drawing-rectangle and apply not drawrectangle method, but fillrectangle, which draws filled rectangle with specified brush/color.

@vfiot

, but I would like the backgroupd color of the rectangle to be black, not transparent.

Just use Graphics.fillRectangle

Thanks for the answers, it solved my issue.