How to draw an image over another image?
If this is Swing, then draw the background image in a BufferedImage. Display this BufferedImage in a JComponent's (such as a JPanel's) paintComponent method using Graphic's drawImage(...)
method, and then draw the changing images over this in the same paintComponent method. Don't forget to call the super.paintComponent(...)
method first though.
Please note that this question has been asked quite a bit here and elsewhere, and as you would expect, there are lots of examples of this sort of thing that you can find here with a bit of searching.
Edit
You ask:
Thanks, this is how I draw the firt image (road)
Again, you would create a BufferedImage for this, likely by using ImageIO.read(...)
. Then you'd draw this in your JPanel's paintComponent(Graphics g)
method override using g.drawImage(...)
.
For example...
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class IntersectionImagePanel extends JPanel {
private static final String INTERSECTION_LINK = "http://www.weinerlawoffice.com/" +
"accident-diagram.jpg";
private BufferedImage intersectionImage;
public IntersectionImagePanel() {
URL imageUrl;
try {
imageUrl = new URL(INTERSECTION_LINK);
intersectionImage = ImageIO.read(imageUrl );
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (intersectionImage != null) {
g.drawImage(intersectionImage, 0, 0, this);
}
}
@Override
public Dimension getPreferredSize() {
if (intersectionImage != null) {
int width = intersectionImage.getWidth();
int height = intersectionImage.getHeight();
return new Dimension(width , height );
}
return super.getPreferredSize();
}
private static void createAndShowGui() {
IntersectionImagePanel mainPanel = new IntersectionImagePanel();
JFrame frame = new JFrame("IntersectionImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
OpenCV draw an image over another image
Use Mat::rowRange()
and Mat::colRange()
to specify the area to which you want to draw in the destination Mat
. Code:
Mat src( 5, 7, CV_8UC1, Scalar(1)); // 5x7
Mat dst(10, 10, CV_8UC1, Scalar(0)); // 10x10
src.copyTo(dst.rowRange(1, 6).colRange(3, 10));
Results in the following:
before copyTo()
:
dst:
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
after copyTo()
:
dst:
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 1 1 1 1 1 1 1 )
( 0 0 0 1 1 1 1 1 1 1 )
( 0 0 0 1 1 1 1 1 1 1 )
( 0 0 0 1 1 1 1 1 1 1 )
( 0 0 0 1 1 1 1 1 1 1 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
( 0 0 0 0 0 0 0 0 0 0 )
Display an image over another image at a particular co-ordinates in openCV
Actually, I found that image homography can be used to do it.
Here is the updated code.
import numpy as np
import cv2
import cv2.aruco as aruco
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
arucoParameters = aruco.DetectorParameters_create()
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=arucoParameters)
if np.all(ids != None):
display = aruco.drawDetectedMarkers(frame, corners)
x1 = (corners[0][0][0][0], corners[0][0][0][1])
x2 = (corners[0][0][1][0], corners[0][0][1][1])
x3 = (corners[0][0][2][0], corners[0][0][2][1])
x4 = (corners[0][0][3][0], corners[0][0][3][1])
im_dst = frame
im_src = cv2.imread("mask.jpg")
size = im_src.shape
pts_dst = np.array([x1,x2,x3,x4])
pts_src = np.array(
[
[0,0],
[size[1] - 1, 0],
[size[1] - 1, size[0] -1],
[0, size[0] - 1 ]
],dtype=float
);
h, status = cv2.findHomography(pts_src, pts_dst)
temp = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.fillConvexPoly(im_dst, pts_dst.astype(int), 0, 16);
im_dst = im_dst + temp
cv2.imshow('Display',im_dst)
else:
display = frame
cv2.imshow('Display',display)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
how to draw image over image in javascript (without CSS and HTML)
Just use drawImage()
with the resize parameters:
context.drawImage(image, point.x, point.y, wantedWidth, wantedHeight);
Image source can be image
or even context
itself.
(Also remember to use onload
handler on the image element before attempting to draw it.)
var ctx = document.querySelector("canvas").getContext("2d"), img = new Image;
img.onload = function() { ctx.drawImage(this, -200, -200, 800, 800); ctx.drawImage(this, 0, 0);};
img.src = "http://i.imgur.com/RV2a28T.png";
<canvas/>
PHP: How to draw an image over another image?
imagecopy()
or imagecopymerge()
. It's documentation brings exemples too.
Drawing a dynamic transparent image over another Image using SWT Graphics
I was able to get the desired result using the method described by Sean Bright here: https://stackoverflow.com/a/15685473/6245535.
Basically:
- we create an image
src
and withgc
we fill it with transparent color - we draw the ovals with solid color
- we get the resulting image data: now, the pixel data array of the image (
imageData.data
) is also going to contain the alpha values, while the alpha data array of the image (imageData.alphaData
) isnull
- we manually fix
imageData.alphaData
by extracting the alpha values at the right positions fromimageData.data
; this part assumes that we are working with 32 bit depth of color; it won't work otherwise - now that the
alphaData
ofimageData
is fixed, we create an imageprocessedImage
with it - with
gc
we finally drawprocessedImage
with partial transparency
Here's the code (which is Sean's code with some changes):
private void drawSecondLayerTake4(GC gc, int x, int y) {
final int width = 300;
final int height = 300;
final Image src = new Image(null, width, height);
final GC imageGC = new GC(src);
imageGC.setAntialias(SWT.ON);
// This sets the alpha on the entire canvas to transparent
imageGC.setAlpha(0);
imageGC.fillRectangle(0, 0, width, height);
// Reset our alpha and draw the ovals
imageGC.setAlpha(255);
imageGC.setBackground(red);
imageGC.fillOval(70, 70, 60, 60);
imageGC.fillOval(100, 100, 60, 60);
// We're done with the GC, so dispose of it
imageGC.dispose();
final ImageData imageData = src.getImageData();
imageData.alphaData = new byte[width * height];
// This is the hacky bit that is making assumptions about
// the underlying ImageData. In my case it is 32 bit data
// so every 4th byte in the data array is the alpha for that
// pixel...
for (int idx = 0; idx < (width * height); idx++) {
final int coord = (idx * 4) + 3;
imageData.alphaData[idx] = imageData.data[coord];
}
// Now that we've set the alphaData, we can create our
// final image
final Image processedImage = new Image(Display.getCurrent(), imageData);
gc.setAlpha(100);
gc.drawImage(processedImage, x + 0, y + 0);
// And get rid of the canvas
src.dispose();
}
And here's the result:
Is it possible to draw images on top of each other?
It is possible to draw image one over the other. You can do draw as many image as you want one over the other.
Basically when you draw the image you need to provide positions. If you provide the same positions for multiple images, depending on the order of the images being drawn, they will be drawn one over the other.
So let's say you have a Tank and its's cannon as separate images. What you will do is draw the tank on the screen. Now you need the cannon image with transparent background and same dimensions as the tank(can be different dimensions) and draw on the same position. That will give an illusion that the cannon is attached to the Tank. Now u can rotate these 2 images separately.
Below is an example :
Sprite tankSprite = new Sprite(new Texture("tank.png"));
Sprite turretSprite = new Sprite(new Texture("turret.png"));
//Set the rotations
tankSprite.setRotation(angle);
turretSprite.setRotation(angle);
//Set the positions
tankSprite.setPosition(x, y);
turretSprite.setPosition(x, y);
//Draw the sprites, using spritebatch
tankSprite.draw(batch); // Drawn first
turretSprite.draw(batch); //Drawn over tank
Let's say this is tank body -
Let's say this is the turret (cannon) -
Now this is the result (ignore the background)-
I have rotated the turret to 90 degrees and tank is at 0 degrees. You can make changes accordingly.
How do I position one image on top of another in HTML?
Ok, after some time, here's what I landed on:
.parent {
position: relative;
top: 0;
left: 0;
}
.image1 {
position: relative;
top: 0;
left: 0;
border: 1px red solid;
}
.image2 {
position: absolute;
top: 30px;
left: 30px;
border: 1px green solid;
}
<div class="parent">
<img class="image1" src="https://via.placeholder.com/50" />
<img class="image2" src="https://via.placeholder.com/100" />
</div>
Related Topics
Why Does 'Java -Version' Go to Stderr
Pageloadtimeout in Selenium Not Working
What Are the Best Use Cases for Akka Framework
Cannot Change Version of Project Facet Dynamic Web Module to 3.0
In Which Case Do You Use the JPA @Jointable Annotation
Understanding Spring @Configuration Class
Charsequence VS String in Java
How to Use Mdc with Thread Pools
Does Java Support Let's Encrypt Certificates
How to Handle Precision Error with Float in Java
Simpledateformat Parse(String Str) Doesn't Throw an Exception When Str = 2011/12/12Aaaaaaaaa
How to Correctly Use Custom Renderers to Paint Specific Cells in a Jtable
How to Properly Configure Implicit/Explicit Waits and Pageloadtimeout Through Selenium
How to Convert a 1D Array to 2D Array
Appearance of Java Security Dialog
How to Get Just the Parent Directory Name of a Specific File