I'm having the user upload an image of a logo and then trying to position it on top of another image I have on the server.
The position where the receipt will be superimposed as parameters by POST. The logo I receive is always a png, which may or may not have a transparent background and the same background must be kept.
The problem: I don't know why it creates black spaces for me, can you tell me what mistake I make?
Code :
session_start();
$posiX = $_POST['x'];
$posiY = $_POST['y'];
$datoImg = $_SESSION['genImg'];
$logo = $datoImg['logo']; //'logo.png'
$fondo = 'original.jpg';
foto($fondo, $logo, $posiX, $posiY);
function foto($img_original, $marcadeagua, $posiX, $posiY){
$trozosimagenorig=explode(".",$img_original);
$extensionimagenorig=$trozosimagenorig[count($trozosimagenorig)-1];
if (preg_match("/jpg|jpeg|JPG|JPEG/", $extensionimagenorig)) {
$imgm=imagecreatefromjpeg($img_original);
}
if (preg_match("/png|PNG/", $extensionimagenorig)) {
$imgm=imagecreatefrompng($img_original);
}
if (preg_match("/gif|GIF/", $extensionimagenorig)) {
$imgm=imagecreatefromgif($img_original);
}
$marcadeagua= imagecreatefrompng($marcadeagua);
$xmarcaagua = $posiX;
$ymarcaagua = $posiY;
$ximagen= imagesx($imgm);
$yimagen=imagesy($imgm);
imagecopy($imgm, $marcadeagua, $xmarcaagua, $ymarcaagua,
0, 0, $xmarcaagua, $ymarcaagua);
//se copia la imagen
imagejpeg($imgm,'../assets/originalrand.jpg');
}
Result obtained: create those black spaces:
Original images:
Background image:
logo image:
The truth is that you almost had it solved. To copy one image over another, use (pay attention to the order of each argument):
I separated the arguments to make it easier to read. The first line takes the image resources (usually generated with
imagecreatefrom***()
). Then the positions in the destination where the image will be located ($dst_x
,$dst_y
), the positions from where it will be taken from the origin ($src_x
,$src_y
), and the dimensions to be taken from the origin ($src_w
,$src_h
).Having this clear, the rest is to locate those values (comment in the code).
Code
Result
I uploaded an example running on free hosting: http://mariano.freevar.com/70835/
Additional features:
serve the image
If instead of generating a file, you wanted PHP to serve the image:
Generate transparent background in the logo if it does not have it
Let's say the logo has a white background. If we wanted all white to be taken as transparent: