Wrong colors when merging images with PHP - php

I want to get images ID's and creat from files a merged image according to the given ID's.
This code is called by ajax and return the image file name (which is the server time to prevent browser caching).
code:
if (isset($_REQUEST['items'])){
$req_items = $_REQUEST['items'];
} else {
$req_items = 'a';
}
$items = explode(',',$req_items);
$bg_img = imagecreatefrompng('bg.png');
for ($i=0; $i<count($items); $i++){
$main_img = $items[$i].'-large.png';
$image = imagecreatefrompng($main_img);
$image_tc = imagecreatetruecolor(300, 200);
imagecopy($image_tc,$image,0,0,0,0,300,200);
$black = imagecolorallocate($image_tc, 0, 0, 0);
imagecolortransparent($image_tc, $black);
$opacity = 100;
$bg_width = 300;
$bg_height = 200;
$dest_x = 0;//$image_size[0] - $bg_width - $padding;
$dest_y = 0;//$image_size[1] - $bg_height - $padding;
imagecopymerge($bg_img, $image_tc, $dest_x, $dest_y, 0, 0, $bg_width, $bg_height, $opacity)
;
}
$file = $_SERVER['REQUEST_TIME'].'.jpg';
imagejpeg($bg_img, $file, 100);
echo $file;
imagedestroy($bg_img);
imagedestroy($image);
die();
The images are shown exactly as I want but with wrong colors. I lately added the part with imagecreatetruecolor and imagecolortransparent, and still got wrong results.
I also saved the PNG itself on a 24 bit format and also later as 8 bit - not helping.
every ideas is very welcomed !
Thanks

After long time of trying... as always the solution was very simple:
Just make the background image a 24 bit as well.
So if someone is looking for a way to make layered transparent images this is the complete code:
<?php
if (isset($_REQUEST['items'])){
$req_items = $_REQUEST['items'];
} else {
$req_items = 'a';
}
$items = explode(',',$req_items);
$bg_img = imagecreatefrompng('bg.png');
$bg_tc = imagecreatetruecolor(300, 200);
imagecopy($bg_tc,$bg_img,0,0,0,0,300,200);
for ($i=0; $i<count($items); $i++){
$main_img = $items[$i].'-large.png';
$image = imagecreatefrompng($main_img);
$image_tc = imagecreatetruecolor(300, 200);
imagecopy($image_tc,$image,0,0,0,0,300,200);
$black = imagecolorallocate($image_tc, 0, 0, 0);
imagecolortransparent($image_tc, $black);
$opacity = 100;
$bg_width = 300;
$bg_height = 200;
$dest_x = 0;//$image_size[0] - $bg_width - $padding;
$dest_y = 0;//$image_size[1] - $bg_height - $padding;
imagecopymerge($bg_tc, $image_tc, $dest_x, $dest_y, 0, 0, $bg_width, $bg_height, $opacity);
}
$file = $_SERVER['REQUEST_TIME'].'.jpg';
imagejpeg($bg_tc, $file, 100);
echo $file;
imagedestroy($image);
imagedestroy($bg_img);
imagedestroy($bg_tc);
imagedestroy($image_tc);
die();
?>

Related

Merging transparent images on PHP

I'm trying to merge of this images:
https://imgur.com/aURQax9 -- Base
https://imgur.com/a/cpiSc -- Marking
the result should look like this:
https://imgur.com/a/ri3zw
I'm getting an image that is removing all of the black color, but I'm unsure how to do this.
$numberOfImages = 2;
$x = 600;
$y = 600;
$background = imagecreatetruecolor($x, $y);
$black = imagecolorallocate($background, 0, 0, 0);
imagecolortransparent($background, $black);
$firstUrl = 'Images/Horses/First horses/Red Breeds/Paint/Adult/Overo/1/BayOvero1AD.png';
$secondUrl = 'Images/Horses/First horses/Red Breeds/Paint/Markings/PaintBlazeAD.png';
$outputImage = $background;
$first = imagecreatefrompng($firstUrl);
$second = imagecreatefrompng($secondUrl);
imagecopymerge($outputImage,$first,0,0,0,0, $x, $y,100);
imagecopymerge($outputImage,$second,0,$y,0,0, $x, $y,100);
imagepng($outputImage, './Images/BayOvero1AD.PaintBlazeAD.png');
imagedestroy($outputImage);
How can I update this so that the color isn't removed and that it merges very similarly to the finished image above?
I have just wrote this for you. One of the images posted was a jpg not a PNG, however that could be to do with imgur, therefore I had to resize it and remove some of the white. Which is why my result didn't look quite right when testing. But it should be fine with your original files:
As you can see, it added the second image above the first, and kept it in the correct posistion.
The code I used for this was:
<?php
$x = 600;
$y = 600;
$firstUrl = 'Images/Horses/First horses/Red Breeds/Paint/Adult/Overo/1/BayOvero1AD.png';
$secondUrl = 'Images/Horses/First horses/Red Breeds/Paint/Markings/PaintBlazeAD.png';
$Image1 = imagecreatefrompng($firstUrl);
$Image2 = imagecreatefrompng($secondUrl);
imagealphablending($Image1, true);
imagesavealpha($Image1, true);
imagecopy($Image1, $Image2, 0, 0, 0, 0, $x, $y);
imagepng($Image1, './Images/BayOvero1AD.PaintBlazeAD.png');
?>

PHP error when creating image using imagecreatetruecolor

I got a simple HTML that calls a image generated from a PHP file but the image is not being displayed. The HTML part is:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="imgcaptcha.php"/>
</body>
</html>
imgcaptcha.php is:
<?php
//error_reporting(E_ALL);
//header('Content-Type: image/png');
//Generates rando string
function geraStringAleatoria($length = 10) {
$charSet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$stringAleatoria = '';
for ($i = 0; $i < $length; $i++) {
$stringAleatoria .= $charSet[rand(0, strlen($charSet) - 1)];
}
return $stringAleatoria;
}
//Generate the captcha image
function geraImagemCaptcha($text = 'good'){
// Set the content-type
$width = 200;
$height = 30;
// Create the image
$im = imagecreatetruecolor($width, $height) or die('display nao instalado');;
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, $width-1, $height-1, $white);
//ADD NOISE - DRAW background squares
$square_count = 6;
for($i = 0; $i < $square_count; $i++){
$cx = rand(0,$width);
$cy = (int)rand(0, $width/2);
$h = $cy + (int)rand(0, $height/5);
$w = $cx + (int)rand($width/3, $width);
imagefilledrectangle($im, $cx, $cy, $w, $h, $white);
}
//ADD NOISE - DRAW ELLIPSES
$ellipse_count = 5;
for ($i = 0; $i < $ellipse_count; $i++) {
$cx = (int)rand(-1*($width/2), $width + ($width/2));
$cy = (int)rand(-1*($height/2), $height + ($height/2));
$h = (int)rand($height/2, 2*$height);
$w = (int)rand($width/2, 2*$width);
imageellipse($im, $cx, $cy, $w, $h, $grey);
}
// Replace path by your own font path
$font = 'flushout.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
}
geraImagemCaptcha(geraStringAleatoria());
?>
I'm using PHP 7
Tried already commenting out header(); call and add error_reporting(E_ALL); but no error message was displayed. Tried also many other different font.ttf files according to this, also didn't worked, so I guess that the problem is in another part of the code rather than the font because I tried many sites and also some other .ttf files I got from other programs installed. The problem is happening in both all browsers I tested. What could be missing in the code? Btw, I got this generate captcha image from here.

Image resize in PHP

I am very new to Resize image in php.Basically i wanted to make thumbnail image using uploaded image. i have used below code but its not working, can anybody help me?..
Thanks in Advance...
$source_image = $path.$row->photosfolder;
$size = getimagesize($source_image);
$w = $size[0];
$h = $size[1];
$simg = imagecreatefromjpeg($source_image);
$dimg = imagecreatetruecolor(150, 225);
$wm = $w / 150;
$hm = $h / 225;
$h_height = 225 / 2;
$w_height = 150 / 2;
if ($w > $h) {
$temp = imagecopyresampled($dimg, $simg, 0, 0, 0, 0, 150, 225, $w, $h);
}
elseif (($w < $h) || ($w == $h)) {
$temp = imagecopyresampled($dimg, $simg, 0, 0, 0, 0, 150, 225, $w, $h);
}
else {
$temp = imagecopyresampled($dimg, $simg, 0, 0, 0, 0, 150, 225, $w, $h);
}
$thumb_image = imagejpeg($dimg, $simg, 100);
check timthumb.php is easy to use and you can find the code full educational
If you want to resize an image, you should do it on client side because PHP image manipulation takes a lot of memory and CPU time, and it doesn't have to be done on server side (there are no access to db, no access to session, etc).
If you still want to do it on PHP, you can use that functions to get the right sizes :
list($realW, $realH) = getimagesize($source_image);
$realR = $realW / $realH;
$thumbR = $thumbW / $thumbH;
// If you want your resize image to fit inside the max thumb size :
if($realR > $thumbR) // Real image if flatter than thumb
{
$newW = $thumbW;
$newH = $newW / $realR;
}
else
{
$newH = $thumbH;
$newW = $newH * $realR;
}
// Or if you want your resize image to be as small as possible but
// not smaller than your thumb. This can be helpful in some cases.
if($realR < $thumbR)
{
// Same code
}
And then use copy resampled as you did (read php manual if you can't get it to work, there are examples below the synopsis of the function).
If you want to resize an image using javascript, you can use the <canvas> :
var canvas = document.createElement('canvas');
var image = document.getElementById('image');
var context = canvas.getContext('2d');
context.save();
context.drawImage(image, /* Here you put the right values using the algorithms above */);
context.restore();
var thumb = document.createElement('image');
thumb.src = canvas.toDataUrl();
Or something like that. You may change a few things depending on your specific case.
Please try with below code, It will resize image and create new thumbnail. New size is defined 100 X 100. This example will also keep aspected ratio of image.
Note:
1.Image path will be directory path if want to set full path.
2. In example we consider for jpg file, you can use for PGN & GIF file with imagecreatefrompng, imagecreatefromgif.
3.This will create PNG file.
$_imagePath = 'somefile.jpg';
$im = imagecreatefromjpeg($_imagePath);
imagealphablending($im, true);
$_orgWidth = imagesx($im);
$_orgHeight = imagesy($im);
$_newWidth = 100;
$_newHeight = 100;
$_finalHeight = $_orgHeight * ( $_newWidth/ $_orgWidth);
if($_finalHeight > $_newHeight){
$_newWidth = $_orgWidth * ($_newHeight / $_orgHeight);
}else{
$_newHeight = $_finalHeight ;
}
$_thumb = imagecreatetruecolor($_newWidth, $_newHeight);
imagealphablending($_thumb, true);
imagesavealpha($_thumb, true);
imagecopyresampled($_thumb, $im, 0, 0, 0, 0, $_newWidth, $_newHeight, $_orgWidth , $_orgHeight );
imagepng($_thumb, 'newname.png');
imagedestroy($_thumb);

imagecopyresampled resizes in chrome crops in ie/ff

i have come across the following problem. i have made an thumbnailer with gd and when i run it in chrome this is what it does:
this is exactly what i expected it to do(resize it)
screenshot taken in chrome
sadly this is what firefox and ie do:(crop it)
image taken in ff
i have the following code taking care of my resize:
// this image is created by another php file when text is filled in
$file = "hidden.png";
$size = GetImageSize($file);
if($size !== false){
$w = $size[0];
$h = $size[1];
//set new size
$nw = $_GET['width'];
$nh = ($nw*$h)/$w;
}
else{
//set new size
$nw = 400;
$nh = 200;
}
//draw the image
$src_img = imagecreatefrompng($file);
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);
//resizing the image
imagepng($dst_img);
imagedestroy($src_img);
imagedestroy($dst_img);
i have searched abit on stack and on google and the only thing i can find are solutions that are using css which i dont need since my image isnt constructed that way.
what do i need to do code-wise(not css related) to get it working correctly in all browsers?
if needed i can post more code
It has definitely nothing to do with the Browser, because that is not the way php works.
First of all the php-code gets interpreted on the server and then the result is past to the Client(Browser).
So in my opinion you should first check if the image generation is working correctly. Means that it produce every time the same Image. Then you should check this part:
if($size !== false){
$w = $size[0];
$h = $size[1];
$nw = $_GET['width']; // <---- For Debugging set here a static number
$nh = ($nw*$h)/$w;
}
Try to set for the debugging part, every variable which could change on each request to a fix value.
I hope i could help you
i solved the question by merging the above script with my allready existing script to generate the image.
/* Get image info */
if(!isset($_POST['width']) && !isset($_POST['height']))
{
$width = '200';
$height = '100';
}
else
{
$width = $_POST['width'] ;
$height = $_POST['height'];
}
$Image = imagecreatetruecolor($width,$height) ;
$sx = imagesx($Image) ;
$sy = imagesy($Image) ;
/*Check if RGB values have been set*/
if(!isset($_POST['r'])) { $R = 255; } else { $R = $_POST['r']; }
if(!isset($_POST['g'])) { $G = 255; } else { $G = $_POST['g']; }
if(!isset($_POST['b'])) { $B = 255; } else { $B = str_replace(")" , "" , $_POST['b']); }
/*Check if the text value is set */
if(!isset($_POST['text'])) {$Text = "Uw tekst hier";}
else if($_POST['text'] == '') {$Text = "Uw tekst hier";}
else {$Text = $_POST['text'];}
/*Check if the font is set */
if(!isset($_POST['font'])) {$Font="./Fonts/arial.ttf" ;}
else{$Font= "./fonts/".$_POST['font'].".ttf";}
$FontColor = ImageColorAllocate ($Image,$R,$G,$B) ; //TextColor
$FontShadow = ImageColorAllocate ($Image,0,0,0) ; //BackGroundColor
$Rotation = 0 ;
/* Iterate to get the size up */
$FontSize=1 ;
do
{
$FontSize *= 1.1 ;
$Box = #ImageTTFBBox($FontSize,0,$Font,$Text);
$TextWidth = abs($Box[2] - $Box[6]) ;
$TextHeight = abs($Box[3] - $Box[7]) ;
}
while ($TextWidth < $sx*0.94) ;
/* Awkward maths to get the origin of the text in the right place */
$x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2;
$y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
imagefilledrectangle($Image, 0, 0, $sx , $sy , $FontShadow);
ImageTTFText ($Image,$FontSize,$Rotation,-$Box[6] ,-$Box[7],$FontColor,$Font,$Text);
if(isset($_POST['resize']) && $_POST['resize'] == 1)
{
$nw = 400;
$nh = 200;
$src_img = $Image;
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $sx, $sy);//resizing the image
imagepng($dst_img, "hidden.png");
imagedestroy($src_img);
imagedestroy($dst_img);
}
else
{
//header('Content-type: image/png');
Imagepng($Image, "hidden.png") ;
}

Adding Watermark to Ajax Crop

Im using Ajax Crop from enter link description here and I'd like to add a watermark to the script. The following is my script.
WATERMARK
$image_path = "watermark.png";
function watermark_image($oldimage_name, $new_image_name){
global $image_path;
list($owidth,$oheight) = getimagesize($oldimage_name);
$width = 500; $height = 100;
$im = imagecreatetruecolor($width, $height);
$img_src = imagecreatefromjpeg($oldimage_name);
imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$watermark = imagecreatefrompng($image_path);
list($w_width, $w_height) = getimagesize($image_path);
$pos_x = $width - $w_width;
$pos_y = $height - $w_height;
imagecopy($im, $watermark, $pos_x, $pos_y, 0, 0, $w_width, $w_height);
imagejpeg($im, $new_image_name, 100);
imagedestroy($im);
unlink($oldimage_name);
return true;
}
UPLOAD AND RESIZE PART
function resizeThumb($arr){
$date = md5(time());
$arr['temp_uploadfile'] = $arr['img_src'];
$arr['new_uploadfile'] = $arr['uploaddir'].strtolower($date).'.jpg';
asidoImg($arr);
exit;
}
I tried adding
$arr = watermark_image($arr['temp_uploadfile'],
$arr['uploaddir'].strtolower($date).'.jpg');
in place of
$arr['new_uploadfile'] = $arr['uploaddir'].strtolower($date).'.jpg';
but this didnt work.
Could someone help me?
Download the files and test
It turns out the script uses ASIDO and it has a built in WATERMARK TOOL.
In func.php I done the following.
function asidoImg2($arr){
include('asido/class.asido.php');
asido::driver('gd');
$height = $arr['height'];
$width = $arr['width'];
$x = $arr['x'];
$y = $arr['y'];
// process
$i1 = asido::image($arr['temp_uploadfile'], $arr['new_uploadfile']);
// fit and add white frame
if($arr['thumb'] === true){
Asido::Crop($i1, $x, $y, $width, $height);
asido::watermark($i1, 'watermark.png', ASIDO_WATERMARK_MIDDLE_LEFT, ASIDO_WATERMARK_SCALABLE_ENABLED, 1);
}
else{
Asido::Frame($i1, $width, $height, Asido::Color(255, 255, 255));
asido::watermark($i1, 'watermark.png', ASIDO_WATERMARK_MIDDLE_LEFT, ASIDO_WATERMARK_SCALABLE_ENABLED, 1);
}
// always convert to jpg
Asido::convert($i1, 'image/jpg');
$i1->Save(ASIDO_OVERWRITE_ENABLED);
$data = array(
'photo'=> $arr['new_uploadfile']
);
// echo $user_id;
// delete old file
echo $data['photo'];
}

Categories