i have php code for upload image and add text watermark, but i have a little problem with the output.
my code success result image with text watermark like this: result 1
but i want the output like this: result 2
this is my code:
function UploadImage($img_name){
$vdir_upload = "img/upload/";
$vfile_upload = $vdir_upload . $img_name;
$file_name = basename($_FILES["img_1"]["name"]);
move_uploaded_file($_FILES["img_1"]["tmp_name"], $vfile_upload);
switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
case "jpg" :
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case "jpeg" :
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case "gif" :
$im_src = imagecreatefromgif($vfile_upload);
break;
case "png" :
$im_src = imagecreatefrompng($vfile_upload);
break;
default :
trigger_error("Error Bad Extention");
exit();
break;
}
$src_width = imageSX($im_src);
$src_height = imageSY($im_src);
$dst_width = 1979;
$dst_height = ($dst_width/$src_width)*$src_height;
$im = imagecreatetruecolor($dst_width,$dst_height);
imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
$font = 'Aliquam.ttf';
$red = imagecolorallocate($im, 255, 0, 0);
imagettftext($im, 30, 0, 10, 50, $red, $font, $_POST["color"]);
imagejpeg($im,$vdir_upload . $_POST["number"].".jpg");
imagedestroy($im_src);
imagedestroy($im);
}
how can I get the result as above? sorry for my bad english, thanks in advance...
First of all - if you want to extend the width of the image by a margin I would take the original width of the image, add the width of your margin (lets call it $extraWidth and assume it is defined somewhere) and adjust your imagecreatetruecolor call with the new width.
Then you allocate a color and fill the remaining space with a rectangle for your color as shown below.
$im = imagecreatetruecolor($dst_width+$extraWidth, $dst_height);
$color = imagecolorallocate($im, 0, 0, 255); // this is blue - change to what you want
imagefilledrectangle($im, $dst_width, 0, $dst_width+$extraWidth, $dst_height, $color);
Please note I have not tested this code, merely referred to the documentation.
$pixel_height_of_character = 30; // change this to actual pixel height of a char
$pixel_gap_between_chars = 3;
$start_from_edge_of_margin = 3;
$string_chars = str_split($_POST['color']);
$start = ($dst_height / 2) - ((count($string_chars) * ($pixel_height_of_character+$pixel_gap_between_chars)) / 2)
// probably should round this
// also need to deduct one half of pixel gap from the result for centering purposes - i think - double check my math.
$left = $start_from_edge_of_margin + $dst_width;
foreach($string_chars as $char){
$top = $start + $pixel_height_of_character;
imagettftext($im, 30, 0, $left, $top, $red, $font, $char);
$start = $top + $pixel_gap_between_chars;
}
So. That is quite a bit to explain.
Basically you calculate the dimensions of each character - then using those dimensions calculate where the first character must start - then draw on the characters one at a time in a loop.
By no means is this code complete - if the provided word is too long it will exceed the bounds of the image so you should test for that. Also it may not get alignments perfect - but it's a good start.
The modified code:
function UploadImage($img_name){
$vdir_upload = "img/upload/";
$vfile_upload = $vdir_upload . $img_name;
$file_name = basename($_FILES["img_1"]["name"]);
move_uploaded_file($_FILES["img_1"]["tmp_name"], $vfile_upload);
switch (strtolower(pathinfo($file_name, PATHINFO_EXTENSION))) {
case "jpg" :
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case "jpeg" :
$im_src = imagecreatefromjpeg($vfile_upload);
break;
case "gif" :
$im_src = imagecreatefromgif($vfile_upload);
break;
case "png" :
$im_src = imagecreatefrompng($vfile_upload);
break;
default :
trigger_error("Error Bad Extention");
exit();
break;
}
$src_width = imageSX($im_src);
$src_height = imageSY($im_src);
$dst_width = 1979;
$dst_height = ($dst_width/$src_width)*$src_height;
$im = imagecreatetruecolor($dst_width+$extraWidth, $dst_height);
$color = imagecolorallocate($im, 0, 0, 255); // this is blue - change to what you want
imagefilledrectangle($im, $dst_width, 0, $dst_width+$extraWidth, $dst_height, $color);
imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
$font = 'Aliquam.ttf';
$red = imagecolorallocate($im, 255, 0, 0);
$pixel_height_of_character = 30; // change this to actual pixel height of a char
$pixel_gap_between_chars = 3;
$start_from_edge_of_margin = 3;
$string_chars = str_split($_POST['color']);
$start = ($dst_height / 2) - ((count($string_chars) * ($pixel_height_of_character+$pixel_gap_between_chars)) / 2)
// probably should round this
// also need to deduct one half of pixel gap from the result for centering purposes - i think - double check my math.
$left = $start_from_edge_of_margin + $dst_width;
foreach($string_chars as $char){
$top = $start + $pixel_height_of_character;
imagettftext($im, 30, 0, $left, $top, $red, $font, $char);
$start = $top + $pixel_gap_between_chars;
}
imagejpeg($im,$vdir_upload . $_POST["number"].".jpg");
imagedestroy($im_src);
imagedestroy($im);
}
class Watermark {
/**
*
* #var image resource
*/
private $image = null;
/**
*
* #var image resource
*/
private $watermark = null;
/**
*
* #var string
*/
private $output_file = null;
/**
*
* #var int
*/
private $type = '';
const BOTTOM_RIGHT = 1;
const CENTER = 2;
const BOTTOM_RIGHT_SMALL = 3;
/**
*
* #param string $path_to_image
*/
public function __construct($path_to_image = ''){
if (file_exists($path_to_image)){
$this->image = $path_to_image;
}
$this->type = Watermark::BOTTOM_RIGHT;
}
/**
*
* #param string $path_to_watermark
* #return boolean
*/
public function setWatermarkImage($path_to_watermark){
if (file_exists($path_to_watermark) && preg_match('/\.png$/i',$path_to_watermark)){
$this->watermark = $path_to_watermark;
return true;
}
return false;
}
/**
*
* #return boolean
*/
public function save(){
$this->output_file = $this->image;
return $this->process();
}
/**
*
* #param string $path_to_image
* #return boolean
*/
public function saveAs($path_to_image){
$this->output_file = $path_to_image;
return $this->process();
}
/**
*
* #param int $type
*/
public function setType($type){
$this->type = $type;
}
/**
*
* #return boolean
*/
private function process(){
$watermark = imagecreatefrompng($this->watermark);
if ($watermark){
$image = imagecreatefromjpeg($this->image);
if ($image){
switch ($this->type){
case Watermark::BOTTOM_RIGHT:
return $this->watermark_bottom_right($image, $watermark);
break;
case Watermark::CENTER:
return $this->watermark_center($image, $watermark);
break;
case Watermark::BOTTOM_RIGHT_SMALL:
return $this->watermark_bottom_right_small($image, $watermark);
break;
}
return true;
}else{
return false;
}
}else {
return false;
}
}
/**
*
* #param image resource $image
* #param image resource $watermark
* #return boolean
*/
private function watermark_bottom_right(&$image, &$watermark){
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$size = getimagesize($this->image);
$dest_x = $size[0] - $watermark_width - 5;
$dest_y = $size[1] - $watermark_height - 5;
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
imagejpeg($image,$this->output_file,100);
imagedestroy($image);
imagedestroy($watermark);
return true;
}
/**
*
* #param image resource $image
* #param image resource $watermark
* #return booelan
*/
private function watermark_center(&$image, &$watermark){
$size = getimagesize($this->image);
$watermark_x = imagesx($watermark);
$watermark_y = imagesy($watermark);
$im_x = $size[0];
$im_y = $size[1];
$cof = $im_x/($watermark_x*1.3); // 5/1 = im_x/(wx*cof) ; wx*cof = im_x/5 ; cof = im_x/wx*5
$w = intval($watermark_x*$cof);
$h = intval($watermark_y*$cof);
$watermark_mini = ImageCreateTrueColor($w, $h);
imagealphablending($watermark_mini, false);
imagesavealpha($watermark_mini,true);
ImageCopyResampled ($watermark_mini, $watermark, 0, 0, 0, 0, $w, $h, $watermark_x, $watermark_y);
$dest_x = $im_x - $w - (($im_x-$w)/2);
$dest_y = $im_y - $h - (($im_y-$h)/2);
imagecopy($image, $watermark_mini, $dest_x, $dest_y, 0, 0, $w, $h);
imagejpeg($image,$this->output_file,100);
imagedestroy($image);
imagedestroy($watermark);
return true;
}
/**
*
* #param image resource $image
* #param image resource $watermark
* #return boolean
*/
private function watermark_bottom_right_small(&$image, &$watermark){
$size = getimagesize($this->image);
$orig_watermark_x = imagesx($watermark);
$orig_watermark_y = imagesy($watermark);
$im_x = $size[0];
$im_y = $size[1];
$cof = $im_x/($orig_watermark_x*5); // 5/1 = im_x/(wx*cof) ; wx*cof = im_x/5 ; cof = im_x/wx*5
$w = intval($orig_watermark_x*$cof);
$h = intval($orig_watermark_y*$cof);
$watermark_mini = ImageCreateTrueColor($w, $h);
imagealphablending($watermark_mini, false);
imagesavealpha($watermark_mini,true);
ImageCopyResampled ($watermark_mini, $watermark, 0, 0, 0, 0, $w, $h, $orig_watermark_x, $orig_watermark_y);
//
$dest_x = $size[0] - $w - 5;
$dest_y = $size[1] - $h -5;
imagecopy($image, $watermark_mini, $dest_x,$dest_y , 0, 0, $w, $h);
imagejpeg($image,$this->output_file,100);
imagedestroy($image);
imagedestroy($watermark);
imagedestroy($watermark_mini);
return true;
}
}
use
$watermark = new Watermark('file_path.jpg');
$watermark->setWatermarkImage('watermark_path.png');
$watermark->setType(Watermark::CENTER);
$watermark->saveAs('file_path.jpg');
Related
There is a system that reshapes images with php. I set the width value. I want it to get the height value automatically. In its current form, there is white space on the right side of some images. how can i lose this space. I want the height value to be scaled automatically.
public function resize(int $width = 0, int $height = 0, $default = '') {
if (!$this->width || !$this->height) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->width;
$scale_h = 1;
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && ($this->mime != 'image/png' && $this->mime != 'image/webp')) {
return;
}
$new_width = (int)($this->width * $scale);
$new_height = (int)($this->height * $scale);
$xpos = 0;
$ypos = 0;
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $new_height);
if ($this->mime == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else if ($this->mime == 'image/webp') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $new_height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->width, $this->height);
imagedestroy($image_old);
$this->width = $width;
$this->height = $new_height;
}
You are most likely missing the $default parameter, it should be 'w'.
As an example:
Let's say you have an image 128 x 128 and want to resize it to 256 (width), it should be scaled up to 256 x 256. The call looks like:
See how the resize scale is calculated:
$scale_w = $width / $this->width; // 256 / 128 = 2
$scale_h = 1;
if ($default == 'w') {
$scale = $scale_w; // = 2
} elseif ($default == 'h') {
$scale = $scale_h; // = 1
} else {
$scale = min($scale_w, $scale_h); // = 1
}
Without 'w' flag $scale becomes 1 and with 'w' flag it becomes 2 - the expected value.
Later on the algorithm uses $width several times instead of $new_width so the new image will be 256w x 128h instead of 128 x 128 due this line:
$this->image = imagecreatetruecolor($width, $new_height);
But imagecopyresampled uses $new_width so you end up with an 256w x 128h image, containing the original 128 x 128 image.
I have a function which adds text under a existing qr-code image.
In some cases the return is faster than the server has written the image on the filesystem, so that other function got issues.
How can I make sure that everything is done before I return the path to the image?
At the moment I am trying to use a while-loop, but I am also really unhappy with it. That causes also timeouts and crashes on my server (no idea why).
function addTextToQrCode($oldImage, $text)
{
$newImage = $oldImage;
$newImage = str_replace(".png", "_original.png", $newImage);
copy($oldImage, $newImage);
$image = imagecreatefrompng($oldImage);
$black = imagecolorallocate($image, 0, 0, 0);
$fontSize = 20;
$textWidth = imagefontwidth($fontSize) * strlen($text);
$textHeight = imagefontheight($fontSize);
$x = imagesx($image) / 2 - $textWidth / 2;
$y = imagesy($image) - $textHeight - 3;
imagestring($image, 5, $x, $y, $text, $black);
$filePath = "/qrCodes/qrcode".$text.'.png';
imagepng($image, $filePath);
while(!$this->checkIfNewQrCodeIsOnFileSystem($filePath)){
$this->checkIfNewQrCodeIsOnFileSystem($filePath);
}
return $filePath;
}
function checkIfNewQrCodeIsOnFileSystem($filePath) {
if (file_exists($filePath)) {
return true;
} else {
return false;
}
}
Check only imagepng(). The solution i would prefer.
function addTextToQrCode($oldImage, $text)
{
$newImage = $oldImage;
$newImage = str_replace(".png", "_original.png", $newImage);
copy($oldImage, $newImage);
$image = imagecreatefrompng($oldImage);
$black = imagecolorallocate($image, 0, 0, 0);
$fontSize = 20;
$textWidth = imagefontwidth($fontSize) * strlen($text);
$textHeight = imagefontheight($fontSize);
$x = imagesx($image) / 2 - $textWidth / 2;
$y = imagesy($image) - $textHeight - 3;
imagestring($image, 5, $x, $y, $text, $black);
$filePath = "/qrCodes/qrcode".$text.'.png';
if (imagepng($image, $filePath) === true) {
return $filePath;
}
}
I've tried experimenting with the GD library to simulate Photoshop's muliply effect, but I haven't found a working solution yet.
According to Wikipedia, the multiply blend mode:
[...] multiplies the numbers for each pixel of the top layer with the corresponding pixel for the bottom layer. The result is a darker picture.
Does anyone know of a way to achieve this using PHP? Any help would be much appreciated.
You need to take every pixel of your image, then multiply each RGB value with your background color / 255 (it's the Photoshop formula). For example, a JPG file with a red background color multiply filter, saved as a PNG file for better results:
<?php
$filter_r=216;
$filter_g=0;
$filter_b=26;
$suffixe="_red";
$path=YOURPATHFILE;
if(is_file($path)){
$image=#imagecreatefromjpeg($path);
$new_path=substr($path,0,strlen($path)-4).$suffixe.".png";
$imagex = imagesx($image);
$imagey = imagesy($image);
for ($x = 0; $x <$imagex; ++$x) {
for ($y = 0; $y <$imagey; ++$y) {
$rgb = imagecolorat($image, $x, $y);
$TabColors=imagecolorsforindex ( $image , $rgb );
$color_r=floor($TabColors['red']*$filter_r/255);
$color_g=floor($TabColors['green']*$filter_g/255);
$color_b=floor($TabColors['blue']*$filter_b/255);
$newcol = imagecolorallocate($image, $color_r,$color_g,$color_b);
imagesetpixel($image, $x, $y, $newcol);
}
}
imagepng($image,$new_path);
}
?>
I've been looking for Multiply blend between two images as well and couldn't find any native-php solution for it. It appears that only way (for now) is to "manually" set pixels, pixel-by-pixel. Here's my code that does Multiply blend between two images, assuming that images are of the same size. You can adjust it to handle different sizes if you like.
function multiplyImage($dst,$src)
{
$ow = imagesx($dst);
$oh = imagesy($dst);
$inv255 = 1.0/255.0;
$c = imagecreatetruecolor($ow,$oh);
for ($x = 0; $x <$ow; ++$x)
{
for ($y = 0; $y <$oh; ++$y)
{
$rgb_src = imagecolorsforindex($src,imagecolorat($src, $x, $y));
$rgb_dst = imagecolorsforindex($dst,imagecolorat($dst, $x, $y));
$r = $rgb_src['red'] * $rgb_dst['red']*$inv255;
$g = $rgb_src['green'] * $rgb_dst['green']*$inv255;
$b = $rgb_src['blue'] * $rgb_dst['blue']*$inv255;
$rgb = imagecolorallocate($c,$r,$g,$b);
imagesetpixel($c, $x, $y, $rgb);
}
}
return $c;
}
Function returns image object so you should ensure to do imagedestroy after you're done using it.
There should be a workaround using overlay native-php blend, which suggests that 50% gray pixels of destination image will be affected by source pixels. In theory, if you do need to blend two black-and-white images (no gray tones), if you set contrast of destination image so white will become 50%-gray, and then overlay-blend source image over it, should give you something similar to multiply. But for color images, or grayscale images, this wouldn't work - above method appears to be the only option.
I was led into this thread when I needed to blend two images in GD. It seems there is no code specifically for that so I will just leave this here for future visitors to this page.
This is a fork from the answer of colivier that supports multiply-blending of two images.
The two images need not be of the same size BUT the overlaying image will be resized and cropped to the size of the bottom layer. I made a fit helper function to do just that but don't bother with that.
imagecolorat returns the base color, even with PNGs with transparency. That is, a 50% black (visible as (128, 128, 128)) will be returned as (0, 0, 0, 64) 64 being the alpha value. This code takes into consideration translucency and converts the translucent colors to the visible color values.
// bottom layer
$img1 = imagecreatefromjpeg(realpath(__DIR__.'/profilePic.jpg'));
// top layer
$img2 = imagecreatefrompng(realpath(__DIR__.'/border2.png'));
imagealphablending($img2, false);
imagesavealpha($img2, true);
$imagex = imagesx($img1);
$imagey = imagesy($img1);
$imagex2 = imagesx($img2);
$imagey2 = imagesy($img2);
// Prereq: Resize img2 to match img1, cropping beyond the aspect ratio
$w1 = max(min($imagex2, $imagex), $imagex);
$h1 = max(min($imagey2, $imagey), $imagey);
$w_using_h1 = round($h1 * $imagex2 / $imagey2);
$h_using_w1 = round($w1 * $imagey2 / $imagex2);
if ($w_using_h1 > $imagex) {
fit($img2, $imagex, $imagey, 'HEIGHT', true);
}
fit($img2, $imagex, $imagey, 'WIDTH', true);
// Actual multiply filter
for ($x = 0; $x < $imagex; ++$x) {
for ($y = 0; $y < $imagey; ++$y) {
$rgb1 = imagecolorat($img1, $x, $y);
$rgb2 = imagecolorat($img2, $x, $y);
$idx1 = imagecolorsforindex($img1, $rgb1);
$idx2 = imagecolorsforindex($img2, $rgb2);
// Shift left 8, then shift right 7
// same as multiply by 256 then divide by 128
// approximate multiply by 255 then divide by 127
// This is basically multiply by 2 but, expanded to show that
// we are adding a fraction of white to the translucent image
// $adder = ($idx2['alpha'] << 8 >> 7);
$adder = ($idx2['alpha'] << 1);
$rmul = min(255, $idx2['red'] + $adder);
$gmul = min(255, $idx2['green'] + $adder);
$bmul = min(255, $idx2['blue'] + $adder);
$color_r = floor($idx1['red'] * $rmul / 255);
$color_g = floor($idx1['green'] * $gmul / 255);
$color_b = floor($idx1['blue'] * $bmul / 255);
$newcol = imagecolorallocatealpha($img1, $color_r, $color_g, $color_b, 0);
imagesetpixel($img1, $x, $y, $newcol);
}
}
imagejpeg($img1, __DIR__.'/out.jpg');
/**
* Fits an image to a $w x $h canvas
*
* #param type $w Target width
* #param type $h Target height
* #param int $fit_which Which dimension to fit
* #param bool $upscale If set to true, will scale a smaller image to fit the given dimensions
* #param bool $padded If set to true, will add padding to achieve given dimensions
*
* #return Image object
*/
function fit(&$img, $w, $h, $fit_which = 'BOTH', $upscale = false, $padded = true) {
if (!in_array($fit_which, array('WIDTH', 'HEIGHT', 'BOTH'))) {
$fit_which = 'BOTH';
}
$w0 = imagesx($img);
$h0 = imagesy($img);
if (!$upscale && $w0 <= $w && $h0 <= $h)
return $this;
if ($padded) {
$w1 = max(min($w0, $w), $w);
$h1 = max(min($h0, $h), $h);
}
else {
$w1 = min($w0, $w);
$h1 = min($h0, $h);
}
$w_using_h1 = round($h1 * $w0 / $h0);
$h_using_w1 = round($w1 * $h0 / $w0);
// Assume width, crop height
if ($fit_which == 'WIDTH') {
$w2 = $w1;
$h2 = $h_using_w1;
}
// Assume height, crop width
elseif ($fit_which == 'HEIGHT') {
$w2 = $w_using_h1;
$h2 = $h1;
}
elseif ($fit_which == 'BOTH') {
if (!$padded) {
$w2 = $w = min($w, $w_using_h1);
$h2 = $h = min($h, $h_using_w1);
}
else {
// Extend vertically
if ($h_using_w1 <= $h) {
$w2 = $w1;
$h2 = $h_using_w1;
}
// Extend horizontally
else {
$w2 = $w_using_h1;
$h2 = $h1;
}
}
}
$im2 = imagecreatetruecolor($w, $h);
imagealphablending($im2, true);
imagesavealpha($im2, true);
$transparent = imagecolorallocatealpha($im2, 255, 255, 255, 127);
imagefill($im2, 0, 0, $transparent);
imagealphablending($img, true);
imagesavealpha($img, true);
// imagefill($im, 0, 0, $transparent);
imagecopyresampled($im2, $img, ($w - $w2) / 2, ($h - $h2) / 2, 0, 0, $w2, $h2, $w0, $h0);
$img = $im2;
}
Have you tried to use php manual?
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.
<?php
function multiplyColor(&$im, $color = array(255, 0, 0)) {
//get opposite color
$opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);
//now we subtract the opposite color from the image
imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
If used with png image and alpha must be well and works very well
$filter_r=215;
$filter_g=5;
$filter_b=5;
$alpha=70;
$suffixe="_red";
$path="./img/foto_220_590.png";
if(is_file($path)){
$image=imagecreatefrompng($path);
$new_path=substr($path,0,strlen($path)-4).$suffixe.".png";
echo $imagex = imagesx($image);
echo $imagey = imagesy($image);
for ($x = 0; $x <$imagex; ++$x) {
for ($y = 0; $y <$imagey; ++$y) {
$rgb = imagecolorat($image, $x, $y);
$TabColors=imagecolorsforindex ( $image , $rgb );
$color_r=floor($TabColors['red']*$filter_r/255);
$color_g=floor($TabColors['green']*$filter_g/255);
$color_b=floor($TabColors['blue']*$filter_b/255);
//$newcol = imagecolorallocate($image, $color_r,$color_g,$color_b);
// this new alpha
$newcol = imagecolorallocatealpha($image, $color_r,$color_g,$color_b,$alpha);
imagesetpixel($image, $x, $y, $newcol);
}
}
imagepng($image,$new_path);
I updated #colivier script to be able to myltiply two images, and not just an image with a color:
/**
* Multiply $pathToDst and $pathToSrc to $resultPath
*
* #param string $pathToDst
* #param string $pathToSrc
* #param string $resultPath
*/
function multiply($pathToDst, $pathToSrc, $resultPath) {
switch (pathinfo($pathToDst, PATHINFO_EXTENSION)) {
case "gif" :
$resourceDst = imagecreatefromgif($pathToDst);
break;
case "png" :
$resourceDst = imagecreatefrompng($pathToDst);
break;
default :
$resourceDst = imagecreatefromjpeg($pathToDst);
break;
}
switch (pathinfo($pathToSrc, PATHINFO_EXTENSION)) {
case "gif" :
$resourceSrc = imagecreatefromgif($pathToSrc);
break;
case "png" :
$resourceSrc = imagecreatefrompng($pathToSrc);
break;
default :
$resourceSrc = imagecreatefromjpeg($pathToSrc);
break;
}
for ($x = 0; $x < 400; ++$x) {
for ($y = 0; $y < 400; ++$y) {
$TabColorsFlag = imagecolorsforindex($resourceDst, imagecolorat($resourceDst, $x, $y));
$TabColorsPerso = imagecolorsforindex($resourceSrc, imagecolorat($resourceSrc, $x, $y));
$color_r = floor($TabColorsFlag['red'] * $TabColorsPerso['red'] / 255);
$color_g = floor($TabColorsFlag['green'] * $TabColorsPerso['green'] / 255);
$color_b = floor($TabColorsFlag['blue'] * $TabColorsPerso['blue'] / 255);
imagesetpixel($resourceDst, $x, $y, imagecolorallocate($resourceSrc, $color_r, $color_g, $color_b));
}
}
imagepng($resourceDst, $resultPath, 0);
imagedestroy($resourceDst);
imagedestroy($resourceSrc);
}
This question already has answers here:
Resize image in PHP
(13 answers)
Closed 6 years ago.
function resize($originalImage){
list($width, $height) = getimagesize($originalImage);
$newName=basename($originalImage);
$imageResized = imagecreatetruecolor(128, 128);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 128, 128, $width, $height);
imagejpeg($imageResized, "resizedImg/$newName",100);
imageDestroy($imageResized);
}
The script returns the image with the correct name but it's just black? Any ideas?
If you have trouble with image resizing use this code for it. Do the modifications as you need it.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}
I am using this function
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagesavealpha($new_image, true);
$trans_colour = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $trans_colour);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
What I want to do is make a square image. I would like to resize by the smallest attribute, then instead of the larger number being squished. I would like the edges chopped off.
So if I have an image which is 213 x 180 which I need resized to 150 x 150
I can resize the image to 150 height before it hits this function.
What I don't know how to do is take the width and chop off the edges to get 150 width without distortion.
Does anyone know how to do this?
By "Chop off" the edge i guess you mean making a crop of you're image, right ?
For croping a image you could use imagecopyresized.
A little example :
$imageSrc = //Your source image;
$tempImage = imagecreatetruecolor(150,150);
// CropStartX et cropStartY have to be computed to suit your needs
imagecopyresized($tempImage,$imageSrc,0,0,$cropStartX,$cropStartY,150,150,150,150);
// $tempImage now contain your cropped image.
This is copied from an old project of mine, does what you need:
static public function resizeCropAndMove($from_path, $to_path, $max_width, $max_height)
{
$image_info = getImageSize($from_path);
switch ($image_info['mime']) {
case 'image/jpeg': $input = imageCreateFromJPEG($from_path); break;
default:
return false;
}
$input_width = imagesx($input);
$input_height = imagesy($input);
$output = imageCreateTrueColor($max_width, $max_height);
if ($input_width <= $input_height) { //portrait
$lamda = $max_width / $input_width;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$top = (int)round(($temp_height - $max_height) / 2);
$left = 0;
}
} else { //landscape
$lamda = $max_height / $input_height;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$left = (int)round(($temp_width - $max_width) / 2);
$top = 0;
}
}
if ($lamda < 1) {
imageCopyResampled($output, $temp, 0, 0, $left, $top, $max_width, $max_height, $max_width, $max_height);
imagePNG($output, $to_path);
imagedestroy($temp);
} else {
imagePNG($input, $to_path);
}
imageDestroy($input);
imageDestroy($output);
}
function createCroppedThumb($thumbSourcePath, $thumbSavePath, $thumbDim){
// Get dimensions of the original image
$detail = getimagesize($thumbSourcePath);
$current_width = $detail[0];
$current_height = $detail[1];
$imageType = $detail[2];
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $thumbDim;
$crop_height = $thumbDim;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
switch($imageType){
case '1':
$current_image = imagecreatefromgif($thumbSourcePath);
break;
case '2':
$current_image = imagecreatefromjpeg($thumbSourcePath);
break;
case '3':
$current_image = imagecreatefrompng($thumbSourcePath);
break;
default:
throw new Exception('unknown image type');
break;
}
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
switch($imageType){
case '1':
imagegif($canvas,$thumbSavePath,100);
break;
case '2':
imagejpeg($canvas,$thumbSavePath,100);
break;
case '3':
imagepng($canvas,$thumbSavePath,100);
break;
default:
throw new Exception('unknown image type');
break;
}
}