Merging two images with PHP - php

I'm trying to merge two images together with PHP.
For example... how would I go about placing image one on top of image two or merge, with basic PHP?
I have tried something such as watermarking, but it doesn't seem to be working.
Image One
Image Two
...and have it turn into this? FINAL RESULT:

I got it working from one I made.
<?php
$dest = imagecreatefrompng('vinyl.png');
$src = imagecreatefromjpeg('cover2.jpg');
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);
?>

Question is about merging two images, however in this specified case you shouldn't do that. You should put Content Image (ie. cover) into <img /> tag, and Style Image into CSS, why?
As I said the cover belongs to the content of the document, while that vinyl record and shadow are just a part of the page styles.
Such separation is much more convenient to use. User can easily copy that image. It's easier to index by web-spiders.
Finally, it's much easier to maintain.
So use a very simple code:
<div class="cover">
<img src="/content/images/covers/movin-mountains.png" alt="Moving mountains by Pneuma" width="100" height="100" />
</div>
.cover {
padding: 10px;
padding-right: 100px;
background: url(/style/images/cover-background.png) no-repeat;
}

ImageArtist is a pure gd wrapper authored by me, this enables you to do complex image manipulations insanely easy, for your question solution can be done using very few steps using this powerful library.
here is a sample code.
$img1 = new Image("./cover.jpg");
$img2 = new Image("./box.png");
$img2->merge($img1,9,9);
$img2->save("./merged.png",IMAGETYPE_PNG);
This is how my result looks like.

You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.
function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {
//$mergeType 0 for horizandal merge 1 for vertical merge
// Get dimensions for specified images
list($width_x, $height_x) = getimagesize($filename_x);
list($width_y, $height_y) = getimagesize($filename_y);
$lowerFileName = strtolower($filename_x);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_x = imagecreatefromjpeg($filename_x);
}else if(substr_count($lowerFileName, '.png')>0){
$image_x = imagecreatefrompng($filename_x);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_x = imagecreatefromgif($filename_x);
}
$lowerFileName = strtolower($filename_y);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_y = imagecreatefromjpeg($filename_y);
}else if(substr_count($lowerFileName, '.png')>0){
$image_y = imagecreatefrompng($filename_y);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_y = imagecreatefromgif($filename_y);
}
if($mergeType==0){
//for horizandal merge
if($height_y<$height_x){
$new_height = $height_y;
$new_x_height = $new_height;
$precentageReduced = ($height_x - $new_height)/($height_x/100);
$new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$height_x = $new_x_height;
$width_x = $new_x_width;
}else{
$new_height = $height_x;
$new_y_height = $new_height;
$precentageReduced = ($height_y - $new_height)/($height_y/100);
$new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$height_y = $new_y_height;
$width_y = $new_y_width;
}
$new_width = $width_x + $width_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);
}else{
//for verical merge
if($width_y<$width_x){
$new_width = $width_y;
$new_x_width = $new_width;
$precentageReduced = ($width_x - $new_width)/($width_x/100);
$new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$width_x = $new_x_width;
$height_x = $new_x_height;
}else{
$new_width = $width_x;
$new_y_width = $new_width;
$precentageReduced = ($width_y - $new_width)/($width_y/100);
$new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$width_y = $new_y_width;
$height_y = $new_y_height;
}
$new_height = $height_x + $height_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);
}
$lowerFileName = strtolower($filename_result);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
imagegif($image, $filename_result);
}
// Clean up
imagedestroy($image);
imagedestroy($image_x);
imagedestroy($image_y);
}
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically

Use the GD library or ImageMagick. I googled 'PHP GD merge images' and got several articles on doing this. In the past what I've done is create a large blank image, and then used imagecopymerge() to paste those images into my original blank one. Check out the articles on google you'll find some source code you can start using right away.

You can do this with the ImageMagick extension. I'm guessing that the combineImages() method will do what you want.

Merger two image png and jpg/png [Image Masking]
//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);
//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
list($src_w, $src_h) = getimagesize($src_url);
//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);
//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);
imagecopymerge_alpha
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
{
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}

The GD Image Manipulation Library in PHP is probably the best for working with images in PHP. Try one of the imagecopy functions (imagecopy, imagecopymerge, ...). Each of them combine 2 images in different ways. See the php documentation on imagecopy for more information.

Related

Black color at cropped borders when using it in gdi, but looks transparent in photo editor

Borrowed this code to circle crop an image output.
// create the transparent circle image
$filename = APP_WEB_PATH."img/user/".$_GET['img'].".jpg";
$imagefilenamepng = APP_WEB_PATH."img/user/".$_GET['img']."_c.png";
$image_s = imagecreatefromstring(file_get_contents($filename));
$width = imagesx($image_s);
$height = imagesy($image_s);
$newwidth = 300;
$newheight = 300;
$image = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($image, true);
imagecopyresampled($image, $image_s, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//create masking
$mask = imagecreatetruecolor($newwidth, $newheight);
$transparent = imagecolorallocate($mask, 255, 0, 0);
imagecolortransparent($mask,$transparent);
imagefilledellipse($mask, $newwidth/2, $newheight/2, $newwidth, $newheight, $transparent);
$red = imagecolorallocate($mask, 0, 0, 0);
imagecopymerge($image, $mask, 0, 0, 0, 0, $newwidth, $newheight, 100);
imagecolortransparent($image,$red);
imagefill($image, 0, 0, $red);
imagepng($image,$imagefilenamepng);
imagedestroy($image);
imagedestroy($mask);
The image looks good and transparent and even when opened with a photo editor
but when used inside an image using php GDI i get a black border instead of transparent
what am I missing here.. (if I use paint.net image editor and re-save the image, then it works fine..) the below image works fine after saving in the photo editor
I use the code to call it as
self::$im = imagecreatefromjpeg($imgname1);
$im2 = imagecreatefrompng($imgname2);
$sx = imagesx($im2)*$scale;
$sy = imagesy($im2)*$scale;
$stamp = imagescale($im2, $sx);
imagecopy(self::$im, $stamp, $xcord, $ycord, 0, 0, $sx, $sy);
here self::$im is the larger image, and $im2 is the one that is cropped

imagecopymerge does not work correctly with partially transparent images

I have an image that has opacity:
When I try load it with:
$img = imagecreatefrompng('cheek-01.png');
header('Content-Type: image/png');
imagepng($img);
it will become:
I want to add (merge) this image with another image (I know how can merge two png images).
What is the problem and how can I load it with GD library without losing opacity?
Update
My goal is merge some images where some of them have alpha (different opacity, like the above image), but when I merge them the alpha information is lost.
<?php
$background = imagecreatetruecolor(3508, 2480);
// set background to white
$white = imagecolorallocate($background, 255, 255, 255);
imagefill($background, 0, 0, $white);
$dest = $background;
$items = array(
'cloth-1763-1249' => 'cloth-01.png',
'skin-167-59' => "skin-01.png",
'cheek-2247-1193' => 'cheek-09.png',
'hair-167-59' => 'hair-07.png'
);
foreach ($items as $i => $item) {
$src = imagecreatefrompng($item);
imagealphablending($src, true);
imagesavealpha($src, true);
imagecolortransparent($src, 2130706432);
$src_x = imagesx($src);
$src_y = imagesy($src);
$list = explode('-', $i);
//var_dump($list);
imagecopymerge($dest, $src, intval($list[1]), intval($list[2]), 0, 0, $src_x, $src_y, 100);
imagealphablending($dest, true);
imagesavealpha($dest, true);
}
header('Content-Type: image/png');
imagepng($dest);
Just use imagecopy function. You can do this because your images have built in transparency and you do not need the "pct" parameter that imagecopymerge function offers.
Your code, simplified:
<?php
$image = imagecreatetruecolor(600, 600);
imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255));
$items = array(
'layer1' => 'test-1.png',
'layer2' => 'test-2.png',
'layer3' => 'test-3.png',
);
foreach ($items as $i => $item) {
$src = imagecreatefrompng($item);
$srcw = imagesx($src);
$srch = imagesy($src);
imagecopy($image, $src, 0, 0, 0, 0, $srcw, $srch);
}
header('Content-Type: image/png');
imagepng($image);
The output PNG image:
The three PNG images used in the above example (the content is 50% transparent and the background is transparent, not white):
You need to enable alpha blending and imagecopymerge was never designed to respect the alpha channel (people tried to fix this back in 2009, but the PHP devs ignored this and said it was intended behaviour). According to the PHP documentation comment section this should work.
<?php
/**
* PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
* by Sina Salek
*
* Bugfix by Ralph Voigt (bug which causes it
* to work only for $src_x = $src_y = 0.
* Also, inverting opacity is not necessary.)
* 08-JAN-2011
*
**/
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
// creating a cut resource
$cut = imagecreatetruecolor($src_w, $src_h);
// copying relevant section from background to the cut resource
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
// copying relevant section from watermark to the cut resource
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
// insert cut resource to destination image
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
// ...Do your previous stuff...
imagecopymerge_alpha(....);
// do the other stuff
/* Output image to browser */
header('Content-type: image/png');
imagepng($imgPng);
?>

Superimposing a php-Generated Image on another image

I have a background jpg image on disk on which I want to superimpose a php-generated png image. Unfortunately, GD's imagepng() function outputs the data directly, so I can't store it in a variable to copy it using imagecopy() or imagecopymerge().
I want a function that generates the png, which I can use with one of the imagecopy() functions, but I don't know how to return the generated png.
Is there a way to do this without writing the generated image to disk?
Thanks.
Ray
<?php
$dest = imagecreatefrompng('vinyl.png');
$src = imagecreatefromjpeg('cover2.jpg');
imagealphablending($dest, false);
imagesavealpha($dest, true);
imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);
?>
you can look at https://stackoverflow.com/a/3876446/1959508 for more info
I had the same problem and have just accomplished what you are after.
I call this function...
imagecopymerge($dest, $src, $x_pos, $y_pos, 0, 0, $src_width, $src_height, 100);
...where $src is the image resource that is created by imagecreatetruecolor() and (in my case, so not sure if this is mandatory) then edited by imagecopyresampled().
My full code block is...
$image_resized = imagecreatetruecolor($final_width, $final_height);
if (($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG)) {
$transparency = imagecolortransparent($image);
$palletsize = imagecolorstotal($image);
if ($transparency >= 0 && $transparency < $palletsize) {
$transparent_color = imagecolorsforindex($image, $transparency);
$transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
imagefill($image_resized, 0, 0, $transparency);
imagecolortransparent($image_resized, $transparency);
} elseif ($info[2] == IMAGETYPE_PNG) {
imagealphablending($image_resized, false);
$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
imagefill($image_resized, 0, 0, $color);
imagesavealpha($image_resized, true);
}
}
imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
// Make white colour transparent
$transparency_color_id = imagecolorallocate($src, 255, 255, 255);
$res = imagecolortransparent($src, $transparency_color_id);
$dest = imagecreatefromjpeg($bg_image_dir . $bg_image_filename);
$x_pos = 1400 - $prod_image_right_margin - $src_width;
$y_pos = (700 - $src_height) / 2;
imagecopymerge($dest, $src, $x_pos, $y_pos, 0, 0, $src_width, $src_height, 100);
...so hopefully you can dig out from that what you need.

Generate image thumbnails with watermarks on the fly in PHP

I'm looking for PHP class (solution) for generating image thumbnails with watermarks on the fly. Any idea ?
I've successfully used this code to add text to an (thumbnail) image:
(note that you'll need to provide a font)
function createImage($in_filename, $out_filename, $width, $height)
{
$src_img = ImageCreateFromJpeg($in_filename);
$old_x = ImageSX($src_img);
$old_y = ImageSY($src_img);
$dst_img = ImageCreateTrueColor($width, $height);
ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $old_x, $old_y);
addWatermark($dst_img);
ImageJpeg($dst_img, $out_filename, 80);
ImageDestroy($dst_img);
ImageDestroy($src_img);
}
function addWatermark($image)
{
$text = "watermark text";
$font = realpath($_SERVER["DOCUMENT_ROOT"] . "/code/COURBD.TTF"); // case sensitive
if ($font == false) return;
$fontSize = 11;
$borderOffset = 4;
$dimensions = ImageTtfBBox($fontSize, 0, $font, $text . "#");
$lineWidth = ($dimensions[2] - $dimensions[0]);
$textX = (ImageSx($image) - $lineWidth) / 2;
$textY = $borderOffset - $dimensions[7];
$white = ImageColorAllocate($image, 240, 240, 240);
ImageTtfText($image, $fontSize, 0, $textX, $textY, $white, $font, $text);
}
Feedback welcome.
You can do this using using the imagecopyresampled() function. Heres a easy and clear tutorial of adding watermark to thumbnails . Also you can use imagettftext() function to use fonts as your watermark
Tutorial Link:
http://www.phpjabbers.com/phpexample.php?eid=20

How do I resize pngs with transparency in PHP?

I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!
$this->image = imagecreatefrompng($filename);
imagesavealpha($this->image, true);
$newImage = imagecreatetruecolor($width, $height);
// Make a new transparent image and turn off alpha blending to keep the alpha channel
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagecolortransparent($newImage, $background);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $newImage;
imagepng($this->image,$filename);
Update
By 'not working' I meant to say the background color changes to black when I resize pngs.
From what I can tell, you need to set the blending mode to false, and the save alpha channel flag to true before you do the imagecolorallocatealpha()
<?php
/**
* https://stackoverflow.com/a/279310/470749
*
* #param resource $image
* #param int $newWidth
* #param int $newHeight
* #return resource
*/
public function getImageResized($image, int $newWidth, int $newHeight) {
$newImg = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($newImg, false);
imagesavealpha($newImg, true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
$src_w = imagesx($image);
$src_h = imagesy($image);
imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
return $newImg;
}
?>
UPDATE : This code is working only on background transparent with opacity = 0. If your image have 0 < opacity < 100 it'll be black background.
Here is a final solution that is working fine for me.
function resizePng($im, $dst_width, $dst_height) {
$width = imagesx($im);
$height = imagesy($im);
$newImg = imagecreatetruecolor($dst_width, $dst_height);
imagealphablending($newImg, false);
imagesavealpha($newImg, true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height);
return $newImg;
}
using imagescale is better compared to imagecopyresampled. No empty image resource required for the resized image, requires only two arguments compared to the ten required by imagecopyresampled. Also produces better quality with smaller sizes. If using PHP 5.5.18 or earlier, or PHP 5.6.2 or earlier, you should provide the height which is the 3rd argument as the aspect ratio calculation was incorrect.
$this->image = imagecreatefrompng($filename);
$scaled = imagescale($this->image, $width);
imagealphablending($scaled, false);
imagesavealpha($scaled, true);
imagepng($scaled, $filename);
The filling of the new image with a transparent colour is also required (as Dycey coded but I'm guessing forgot to mention :)), not just the 'strategic' saving by itself.
IIRC, you also need to be sure PNGs are 24bit, ie truecolor, and not 8bit to avoid buggy behaviour.
old thread, but just in case - Dycey's example should work, if you name things correctly. Here is a modified version used in my image resizing class. Notice the check to make sure imagecolorallocatealpha() is defined, which it won't be if you are using GD <2.0.8
/**
* usually when people use PNGs, it's because they need alpha channel
* support (that means transparency kids). So here we jump through some
* hoops to create a big transparent rectangle which the resampled image
* will be copied on top of. This will prevent GD from using its default
* background, which is black, and almost never correct. Why GD doesn't do
* this automatically, is a good question.
*
* #param $w int width of target image
* #param $h int height of target image
* #return void
* #private
*/
function _preallocate_transparency($w, $h) {
if (!empty($this->filetype) && !empty($this->new_img) && $this->filetype == 'image/png')) {
if (function_exists('imagecolorallocatealpha')) {
imagealphablending($this->new_img, false);
imagesavealpha($this->new_img, true);
$transparent = imagecolorallocatealpha($this->new_img, 255, 255, 255, 127);
imagefilledrectangle($this->new_img, 0, 0, $tw, $th, $transparent);
}
}
}
It's probably related to the newer versions of PHP (I tested with PHP 5.6) but this now works without the need to fill the image with a transparent background:
$image_p = imagecreatetruecolor(480, 270);
imageAlphaBlending($image_p, false);
imageSaveAlpha($image_p, true);
$image = imagecreatefrompng('image_with_some_transaprency.png');
imagecopyresampled($image_p, $image, 0, 0, 0, 0, 480, 270, 1920, 1080);
imagepng($image_p, 'resized.png', 0);
this is also not working for me :(
thisis my solution.. but i also get a black background and the image is not transparent
<?php
$img_id = 153;
$source = "images/".$img_id.".png";
$source = imagecreatefrompng($source);
$o_w = imagesx($source);
$o_h = imagesy($source);
$w = 200;
$h = 200;
$newImg = imagecreatetruecolor($w, $h);
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $w, $h, $transparent);
imagecopyresampled($newImg, $source, 0, 0, 0, 0, $w, $h, $o_w, $o_h);
imagepng($newImg, $img_id.".png");
?>
<img src="<?php echo $img_id.".png" ?>" />
Here is full code working for png files with preserving their images transparency..
list($width, $height) = getimagesize($filepath);
$new_width = "300";
$new_height = "100";
if($width>$new_width && $height>$new_height)
{
$image_p = imagecreatetruecolor($new_width, $new_height);
imagealphablending($image_p, false);
imagesavealpha($image_p, true);
$image = imagecreatefrompng($filepath);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagepng($image_p,$filepath,5);
}
Full example. Notice that for some png images found on internet it works incorrect, but for my own created with photoshop it works fine.
header('Content-Type: image/png');
$filename = "url to some image";
$newWidth = 300;
$newHeight = 300;
$imageInfo = getimagesize($filename);
$image = imagecreatefrompng($filename); //create source image resource
imagesavealpha($image, true); //saving transparency
$newImg = imagecreatetruecolor($newWidth, $newHeight); //creating conteiner for new image
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); //seting transparent background
imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $imageInfo[0], $imageInfo[1]);
imagepng($newImg); //printout image string
You can simply resize the image with imagescale()
This code works fine for me:
$image = imagescale($image, 720, -1, IMG_BICUBIC);
imagepng($image);
Nor the above solution worked for me. This is the way what i found out to solve the issue.
// upload directory
$upload_dir = "../uploads/";
// valid image formats
$valid_formats = array("jpg", "jpeg", "png");
// maximum image size 1 mb
$max_size = 1048576;
// crop image width, height
$nw = $nh = 800;
$nw1 = $nh1 = 400;
$nw3 = $nh3 = 200;
$nw2 = $nh2 = 100;
// checks that if upload_dir a directory/not
if (is_dir($upload_dir) && is_writeable($upload_dir)) {
// not empty file
if (!empty($_FILES['image'])) {
// assign file name
$name = $_FILES['image']['name'];
// $_FILES to execute all files within a loop
if ($_FILES['image']['error'] == 4) {
$message = "Empty FIle";
}
if ($_FILES['image']['error'] == 0) {
if ($_FILES['image']['size'] > $max_size) {
echo "E-Image is too large!<br>";
$_SESSION['alert'] = "Image is too large!!";
} else if (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {
$_SESSION['alert'] = "This image is not a valid image format!!";
echo "E-This image is not a valid image format<br>";
} else if (file_exists($upload_dir . $name)) {
$_SESSION['alert'] = "Image already exists!!";
echo "E-Image already exists<br>";
} else { // No error found! Move uploaded files
$size = getimagesize($_FILES['image']['tmp_name']);
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
$h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
// path for big image
$big_image_path = $upload_dir . "big/" . $name;
// medium image path
$medium_image_path = $upload_dir . "medium/" . $name;
// small image path
$small_image_path = $upload_dir . "small/" . $name;
// check permission
if (!is_dir($upload_dir . "big/") && !is_writeable($upload_dir . "big/")) {
mkdir($upload_dir . "big/", 0777, false);
}
if (!is_dir($upload_dir . "medium/") && !is_writeable($upload_dir . "medium/")) {
mkdir($upload_dir . "medium/", 0777, false);
}
if (!is_dir($upload_dir . "small/") && !is_writeable($upload_dir . "small/")) {
mkdir($upload_dir . "small/", 0777, false);
}
// image raw data from form
$data = file_get_contents($_FILES["image"]["tmp_name"]);
// create image
$vImg = imagecreatefromstring($data);
//create big image
$dstImg = imagecreatetruecolor($nw, $nh);
imagealphablending($dstImg, false);
$trans_colour = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
imagefilledrectangle($dstImg, 0, 0, $w, $h, $trans_colour);
imagesavealpha($dstImg, true);
imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
imagepng($dstImg, $big_image_path);
//create medium thumb
$dstImg1 = imagecreatetruecolor($nw1, $nh1);
imagealphablending($dstImg1, false);
$trans_colour1 = imagecolorallocatealpha($dstImg1, 0, 0, 0, 127);
imagefilledrectangle($dstImg1, 0, 0, $w, $h, $trans_colour1);
imagesavealpha($dstImg1, true);
imagecopyresampled($dstImg1, $vImg, 0, 0, $x, $y, $nw1, $nh1, $w, $h);
imagepng($dstImg1, $medium_image_path);
// create smallest thumb
$dstImg2 = imagecreatetruecolor($nw2, $nh2);
imagealphablending($dstImg2, false);
$trans_colour2 = imagecolorallocatealpha($dstImg2, 0, 0, 0, 127);
imagefilledrectangle($dstImg2, 0, 0, $w, $h, $trans_colour2);
imagesavealpha($dstImg2, true);
imagecopyresampled($dstImg2, $vImg, 0, 0, $x, $y, $nw2, $nh2, $w, $h);
imagepng($dstImg2, $small_image_path);
/*
* Database insertion
*/
$sql = "INSERT INTO tbl_inksand_product_gallery ("
. "Product_Id,Gallery_Image_Big,Gallery_Image_Medium,Gallery_Image_Thumb,"
. "Gallery_Status,Created_By,Created_Datetime"
. ") VALUES ("
. "'{$Product_Id}','{$big_image_path}','{$medium_image_path}','{$small_image_path}',"
. "'A','$Created_By','{$time}'"
. ")";
db_query($sql);
if (db_affected_rows() == 1) {
if (imagedestroy($dstImg)) {
$_SESSION['success'] = "Image uploaded successfully.";
echo "S-Image uploaded successfully<br>";
} else {
$_SESSION['alert'] = "Image not uploaded!!";
echo "S-Image not uploaded";
}
} else {
$_SESSION['alert'] = "Error in uploading image!!";
echo "E-Error in uploading image!!";
}
}
}
}
} else {
mkdir($upload_dir, 0777);
}

Categories