/** * Method to apply a background color to an image resource. * * @param array $options An array of options for the filter. * color Background matte color * * @return void * * @since 3.4 * @throws InvalidArgumentException * @deprecated 5.0 Use Joomla\Image\Filter\Backgroundfill::execute() instead */ public function execute(array $options = array()) { // Validate that the color value exists and is an integer. if (!isset($options['color'])) { throw new InvalidArgumentException('No color value was given. Expected string or array.'); } $colorCode = !empty($options['color']) ? $options['color'] : null; // Get resource dimensions $width = imagesX($this->handle); $height = imagesY($this->handle); // Sanitize color $rgba = $this->sanitizeColor($colorCode); // Enforce alpha on source image if (imageIsTrueColor($this->handle)) { imageAlphaBlending($this->handle, false); imageSaveAlpha($this->handle, true); } // Create background $bg = imageCreateTruecolor($width, $height); imageSaveAlpha($bg, empty($rgba['alpha'])); // Allocate background color. $color = imageColorAllocateAlpha($bg, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']); // Fill background imageFill($bg, 0, 0, $color); // Apply image over background imageCopy($bg, $this->handle, 0, 0, 0, 0, $width, $height); // Move flattened result onto curent handle. // If handle was palette-based, it'll stay like that. imageCopy($this->handle, $bg, 0, 0, 0, 0, $width, $height); // Free up memory imageDestroy($bg); return; }
function allocateColorAlpha($R, $G = null, $B = null, $A = null) { if (is_array($R)) { return imageColorAllocateAlpha($this->handle, $R['red'], $R['green'], $R['blue'], $R['alpha']); } else { return imageColorAllocateAlpha($this->handle, $R, $G, $B, $A); } }
function init() { session_write_close(); parent::init(); $options = $this->options; $font_path = $this->getFontPath(); $options['desired_width'] = round($options['desired_width']); // $text = $this->wrap($options['font_size'],$options['rotation_angle'],$font_path,$options['text'],$options['desired_width']); // $width_height = $this->getTextBoxWidthHeight($options['text'],$font_path); $options['halign'] = $options['alignment_center'] == true ? 'center' : ($options['alignment_right'] == 'right' ? 'right' : 'left'); /* Calculating height of the of the box */ $im = imagecreatetruecolor($options['desired_width'], 10); imagesavealpha($im, true); $backgroundColor = imagecolorallocatealpha($im, 255, 255, 255, 127); imagefill($im, 0, 0, $backgroundColor); $this->phpimage = $im; $box = new \GDText\Box($this->phpimage); $box->setFontFace($font_path); $rgb_color_array = $this->hex2rgb($options['text_color']); $box->setFontColor(new \GDText\Color($rgb_color_array[0], $rgb_color_array[1], $rgb_color_array[2])); $box->setFontSize($options['font_size']); $box->setBox(0, 0, $options['desired_width'], 0); $box->setTextAlign($options['halign'], 'top'); if ($options['underline']) { $box->setUnderline(); } // $h = $box->draw($options['text']); $this->new_height = $h = $box->getBoxHeight($options['text']); //CREATING DEFAULT IMAGES $im = imagecreatetruecolor($options['desired_width'], $h); imagesavealpha($im, true); $backgroundColor = imagecolorallocatealpha($im, 255, 255, 255, 127); imagefill($im, 0, 0, $backgroundColor); $this->phpimage = $im; $box = new \GDText\Box($this->phpimage); $box->setFontFace($font_path); $rgb_color_array = $this->hex2rgb($options['text_color']); $box->setFontColor(new \GDText\Color($rgb_color_array[0], $rgb_color_array[1], $rgb_color_array[2])); // $box->setTextShadow(new \GDText\Color(0, 0, 0, 50), 2, 2); $box->setFontSize($options['font_size']); // $box->enableDebug(); $box->setBox(0, 0, $options['desired_width'], $h); $box->setTextAlign($options['halign'], 'top'); if ($options['underline']) { $box->setUnderline(); } $box->draw($options['text']); if ($options['rotation_angle']) { $this->phpimage = imagerotate($this->phpimage, $options['rotation_angle'], imageColorAllocateAlpha($im, 255, 255, 255, 127)); imagealphablending($this->phpimage, false); imagesavealpha($this->phpimage, true); } }
protected function _getColor(Image_3D_Color $color, $alpha = 1.0) { $values = $color->getValues(); $values[0] = (int) round($values[0] * 255); $values[1] = (int) round($values[1] * 255); $values[2] = (int) round($values[2] * 255); $values[3] = (int) round((1 - (1 - $values[3]) * $alpha) * 127); if ($values[3] > 0) { // Tranzparente Farbe allokieren $color = imageColorExactAlpha($this->_image, $values[0], $values[1], $values[2], $values[3]); if ($color === -1) { // Wenn nicht Farbe neu alloziieren $color = imageColorAllocateAlpha($this->_image, $values[0], $values[1], $values[2], $values[3]); } } else { // Deckende Farbe allozieren $color = imageColorExact($this->_image, $values[0], $values[1], $values[2]); if ($color === -1) { // Wenn nicht Farbe neu alloziieren $color = imageColorAllocate($this->_image, $values[0], $values[1], $values[2]); } } return $color; }
/** * Method to resize the current image. * * @param mixed $width The width of the resized image in pixels or a percentage. * @param mixed $height The height of the resized image in pixels or a percentage. * @param boolean $createNew If true the current image will be cloned, resized and returned; else * the current image will be resized and returned. * @param integer $scaleMethod Which method to use for scaling * * @return KunenaImage * * @since 11.3 * @throws LogicException */ public function resize($width, $height, $createNew = true, $scaleMethod = self::SCALE_INSIDE) { $config = KunenaFactory::getConfig(); switch ($config->avatarresizemethod) { case '0': $resizemethod = 'imagecopyresized'; break; case '1': $resizemethod = 'imagecopyresampled'; break; default: $resizemethod = 'self::imageCopyResampledBicubic'; break; } // Make sure the resource handle is valid. if (!$this->isLoaded()) { throw new LogicException('No valid image was loaded.'); } // Sanitize width. $width = $this->sanitizeWidth($width, $height); // Sanitize height. $height = $this->sanitizeHeight($height, $width); // Prepare the dimensions for the resize operation. $dimensions = $this->prepareDimensions($width, $height, $scaleMethod); // Instantiate offset. $offset = new stdClass(); $offset->x = $offset->y = 0; // Get truecolor handle $handle = imagecreatetruecolor($dimensions->width, $dimensions->height); // Center image if needed and create the new truecolor image handle. if ($scaleMethod == self::SCALE_FIT) { // Get the offsets $offset->x = round(($width - $dimensions->width) / 2); $offset->y = round(($height - $dimensions->height) / 2); // Make image transparent, otherwise cavas outside initial image would default to black if (!$this->isTransparent()) { $transparency = imagecolorAllocateAlpha($this->handle, 0, 0, 0, 127); imagecolorTransparent($this->handle, $transparency); } } $imgProperties = self::getImageFileProperties($this->getPath()); if ($imgProperties->mime == MIME_GIF) { $trnprt_indx = imagecolortransparent($this->handle); if ($trnprt_indx >= 0 && $trnprt_indx < imagecolorstotal($this->handle)) { $trnprt_color = imagecolorsforindex($this->handle, $trnprt_indx); $trnprt_indx = imagecolorallocate($handle, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); imagefill($handle, 0, 0, $trnprt_indx); imagecolortransparent($handle, $trnprt_indx); } } elseif ($imgProperties->mime == MIME_PNG) { imagealphablending($handle, false); imagesavealpha($handle, true); if ($this->isTransparent()) { $transparent = imagecolorallocatealpha($this->handle, 255, 255, 255, 127); imagefilledrectangle($this->handle, 0, 0, $width, $height, $transparent); } } if ($this->isTransparent()) { $trnprt_indx = imagecolortransparent($this->handle); if ($trnprt_indx >= 0 && $trnprt_indx < imagecolorstotal($this->handle)) { // Get the transparent color values for the current image. $rgba = imageColorsForIndex($this->handle, imagecolortransparent($this->handle)); $color = imageColorAllocateAlpha($handle, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']); } else { $color = imageColorAllocateAlpha($handle, 255, 255, 255, 127); } // Set the transparent color values for the new image. imagecolortransparent($handle, $color); imagefill($handle, 0, 0, $color); imagecopyresized($handle, $this->handle, $offset->x, $offset->y, 0, 0, $dimensions->width, $dimensions->height, $this->getWidth(), $this->getHeight()); } else { call_user_func_array($resizemethod, array(&$handle, &$this->handle, $offset->x, $offset->y, 0, 0, $dimensions->width, $dimensions->height, $this->getWidth(), $this->getHeight())); } // If we are resizing to a new image, create a new KunenaImage object. if ($createNew) { // @codeCoverageIgnoreStart $new = new KunenaImage($handle); return $new; // @codeCoverageIgnoreEnd } else { // Free the memory from the current handle $this->destroy(); $this->handle = $handle; return $this; } }
if ($px >= $py) { $py /= $px; $px = 1.0; } else { $px /= $py; $py = 1.0; } # Calculating our new positions $x += ($width - $width * $py) * 0.5; $y += ($height - $height * $px) * 0.5; $width = $width * $py; $height = $height * $px; break; } # Rotating if we need to rotate $tmpimg->image = imagerotate($tmpimg->image, 360 - $rotate, imageColorAllocateAlpha($tmpimg->image, 0, 0, 0, 127)); # Adding to our main image $img->draw($tmpimg->image, $y . ' ' . $x . ' ' . $width . ' ' . $height); } # Making sure we have our open directories $parent_id = 0; $path = '/'; $dir = explode('/', $_JPOST->dir); for ($i = 1, $directories = count($dir); $i < $directories; $i++) { # Checking to see if our path exists $name = $dir[$i]; $query = "\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM \n\t\t\t\t\t" . NQ_DIRECTORY_TABLE . "\n\t\t\t\tWHERE\n\t\t\t\t\t`app_id`\t=" . (int) $G_APP_DATA['id'] . " AND\n\t\t\t\t\t`environment`\t='" . mysqli_escape_string($G_STORAGE_CONTROLLER_DBLINK, $G_APP_ENVIRONMENT) . "' AND\n\t\t\t\t\t`path`\t\t='" . mysqli_escape_string($G_STORAGE_CONTROLLER_DBLINK, $path) . "' AND\n\t\t\t\t\t`name`\t\t='" . mysqli_escape_string($G_STORAGE_CONTROLLER_DBLINK, str_replace(str_split(NQ_INVALID_PATH_CHARS), '', $name)) . "'\n\t\t\t\tLIMIT 1"; $directory_data = mysqli_single_result_query($G_STORAGE_CONTROLLER_DBLINK, $query); # If we aren't allowed we exit check_directory_blacklisted($G_CONTROLLER_DBLINK, $G_TOKEN_DATA['id'], $G_TOKEN_SESSION_DATA, $directory_data['path'] . $directory_data['name']); # If it doesn't we add it
$charImageStep = $imageWidth / ($charsNumber + 1); $charWritePoint = $charImageStep; // Write captcha characters to the image for ($i = 0; $i < $charsNumber; $i++) { $nextChar = $characters[mt_rand(0, count($characters) - 1)]; $captchaText .= $nextChar; // Font properties $randomFontSize = mt_rand(25, 30); // Random character size to spice things a little bit :) $randomFontAngle = mt_rand(-25, 25); // Twist the character a little bit $fontType = select_captcha_font(); // This is the font we are using - we need to point to the ttf file here // Pixels $pixelX = $charWritePoint; // We will write a character at this X point $pixelY = 40; // We will write a character at this Y point // Random character color // R // G // B // Alpha $randomCharColor = imageColorAllocateAlpha($captchaImage, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 25)); // Write a character to the image imageTtfText($captchaImage, $randomFontSize, $randomFontAngle, $pixelX, $pixelY, $randomCharColor, $fontType, $nextChar); // Increase captcha step $charWritePoint += $charImageStep; } // Add currently generated captcha text to the session $_SESSION['login_captcha'] = $captchaText; // Return the image return imagePng($captchaImage); // Destroy captcha image imageDestroy($captchaImage);
protected function create_images($text, $hash) { // Check parameters. if (trim($text) === '') { return array(); } if (!mb_check_encoding($text, 'UTF-8')) { throw new IMGTextException('String is not valid UTF-8'); } $font_filename = $this->font_dir . '/' . $this->font_name . '.' . $this->font_ext; if (!file_exists($font_filename)) { throw new IMGTextException('Font not found: ' . $font); } $font_size = (int) $this->font_size; if ($font_size <= 0) { throw new IMGTextException('Invalid font size: ' . $size); } if (!preg_match('/^#?(?:[0-9a-f]{3})(?:[0-9a-f]{3})?$/', $this->color)) { throw new IMGTextException('Invalid text color: ' . $this->color); } if ($this->background_color !== false && !preg_match('/^#?(?:[0-9a-f]{3})(?:[0-9a-f]{3})?$/', $this->background_color)) { throw new IMGTextException('Invalid background color: ' . $this->background_color); } if (!is_array($this->padding) || count($this->padding) != 4) { throw new IMGTextException('Invalid padding. Please use array with 4 members.'); } if (!is_array($this->shadow_offset) || count($this->shadow_offset) != 2) { throw new IMGTextException('Invalid shadow offset. Please use array with 2 members.'); } if ($this->shadow_opacity < 0 || $this->shadow_opacity > 127) { throw new IMGTextException('Invalid shadow opacity. Please use a value between 0 (opaque) and 127 (transparent).'); } // Split the text into words. $words = preg_split('/\\s+/u', $text); // Parse the padding amount. $padding_top = intval($this->padding[0]); $padding_right = intval($this->padding[1]); $padding_bottom = intval($this->padding[2]); $padding_left = intval($this->padding[3]); // Get size information for each word. We do this first, in order to find out the maximum height. $fragments = array(); $max_height = 0; $max_top = 0; foreach ($words as $w) { $w = trim($w); if ($w === '') { continue; } // Get the bounding box size. $bounds = imageTTFBBox($font_size, 0, $font_filename, $w); // Get more useful information from GD's return values. $width = $bounds[2] - $bounds[0]; $height = $bounds[3] - $bounds[5]; $left = -$bounds[6] - 1; $top = -$bounds[7] - 1; // Update the max height/top values if necessary. if ($height > $max_height) { $max_height = $height; } if ($top > $max_top) { $max_top = $top; } $fragments[] = array($w, $width, $height, $left, $top); } // Create images for each word. $count = 1; $return = array(); foreach ($fragments as $f) { list($w, $width, $height, $left, $top) = $f; $img_width = $width + $padding_left + $padding_right; $img_height = $this->image_height ? $this->image_height : $max_height + $padding_top + $padding_bottom; $text_left = $left + $padding_left; $text_top = $max_top + $padding_top; // Adjust image size and text location if there's a shadow. if ($this->shadow) { if ($this->shadow_offset[0] < 0) { $shadow_space_left = $this->shadow_blur - $this->shadow_offset[0]; $shadow_space_right = max(0, $this->shadow_blur + abs($this->shadow_offset[0])); $shadow_left = $text_left + $shadow_space_left; $text_left = $text_left + $shadow_space_left - $this->shadow_offset[0]; } else { $shadow_space_left = max(0, $this->shadow_blur - $this->shadow_offset[0]); $shadow_space_right = $this->shadow_blur + $this->shadow_offset[0]; $shadow_left = $text_left + $shadow_space_left + $this->shadow_offset[0]; $text_left = $text_left + $shadow_space_left; } if ($this->shadow_offset[1] < 0) { $shadow_space_top = $this->shadow_blur - $this->shadow_offset[1]; $shadow_space_bottom = max(0, $this->shadow_blur + abs($this->shadow_offset[1])); $shadow_top = $text_top + $shadow_space_top; $text_top = $text_top + $shadow_space_top - $this->shadow_offset[1]; } else { $shadow_space_top = max(0, $this->shadow_blur - $this->shadow_offset[1]); $shadow_space_bottom = $this->shadow_blur + $this->shadow_offset[1]; $shadow_top = $text_top + $shadow_space_top + $this->shadow_offset[1]; $text_top = $text_top + $shadow_space_top; } $img_width += $shadow_space_left + $shadow_space_right; $img_height += $shadow_space_top + $shadow_space_bottom; } // Initialize the image and draw the background. $img = imageCreateTrueColor($img_width, $img_height); if ($this->background_color === false) { imageSaveAlpha($img, true); imageAlphaBlending($img, false); $img_background_color = imageColorAllocateAlpha($img, 255, 255, 255, 127); imageFilledRectangle($img, 0, 0, $img_width, $img_height, $img_background_color); imageAlphaBlending($img, true); } else { $img_background_colors = $this->hex2rgb($this->background_color); $img_background_color = imageColorAllocate($img, $img_background_colors[0], $img_background_colors[1], $img_background_colors[2]); imageFilledRectangle($img, 0, 0, $img_width, $img_height, $img_background_color); } // Draw the shadow. if ($this->shadow) { // Blurred shadow on a transparent background needs special treatment because of GD's limitations. if ($this->shadow_blur && $this->background_color === false) { // Create a temporary image for the shadow. $temp = imageCreateTrueColor($img_width, $img_height); imageSaveAlpha($temp, true); imageFilledRectangle($temp, 0, 0, $img_width, $img_height, imageColorAllocate($temp, 127, 127, 127)); // Draw the shadow text on the temporary image, and blur it. $temp_text_color = imageColorAllocate($temp, $this->shadow_opacity, $this->shadow_opacity, $this->shadow_opacity); imageTTFText($temp, $font_size, 0, $shadow_left, $shadow_top, $temp_text_color, $font_filename, $w); for ($i = 0; $i < $this->shadow_blur; $i++) { imageFilter($temp, IMG_FILTER_GAUSSIAN_BLUR); } // Use the blurred shadow as an alpha mask on the original image. $shadow_colors = $this->hex2rgb($this->shadow_color); for ($x = 0; $x < $img_width; $x++) { for ($y = 0; $y < $img_height; $y++) { $alpha = imageColorAt($temp, $x, $y) & 0xff; imageSetPixel($img, $x, $y, imageColorAllocateAlpha($img, $shadow_colors[0], $shadow_colors[1], $shadow_colors[2], $alpha)); } } imageDestroy($temp); } else { $shadow_colors = $this->hex2rgb($this->shadow_color); $shadow_color = imageColorAllocateAlpha($img, $shadow_colors[0], $shadow_colors[1], $shadow_colors[2], $this->shadow_opacity); imageTTFText($img, $font_size, 0, $shadow_left, $shadow_top, $shadow_color, $font_filename, $w); for ($i = 0; $i < $this->shadow_blur; $i++) { imageFilter($img, IMG_FILTER_GAUSSIAN_BLUR); } } } // Draw the word. $text_colors = $this->hex2rgb($this->color); $text_color = imageColorAllocate($img, $text_colors[0], $text_colors[1], $text_colors[2]); imageTTFText($img, $font_size, 0, $text_left, $text_top, $text_color, $font_filename, $w); // Save to a PNG file. $filename = '/imgtext.' . $hash . '.word-' . str_pad($count, 3, '0', STR_PAD_LEFT) . '.png'; imagePNG($img, $this->cache_local_dir . $filename); imageDestroy($img); // Add information about this word to the return array. $return[] = array('word' => $w, 'path' => $this->cache_url_prefix . $filename); $count++; } // Returns a list of dictionaries, each containing a word and the corresponding image URL. return $return; }
/** * 给图片加水印 * @author 肖飞 * @param string $sourFile 图片文件名 * @param string $text 文本数组(包含二个字符串) * @return 1 成功 成功时返回生成的图片路径 */ function waterMark($sourFile, $text) { $imageInfo = $this->getInfo($sourFile); $sourFile = $this->sourcePath . $sourFile; // $newName = substr($imageInfo["name"], 0, strrpos($imageInfo["name"], ".")) . "_mark.jpg"; switch ($imageInfo["type"]) { case 1: //gif $img = imagecreatefromgif($sourFile); break; case 2: //jpg $img = imagecreatefromjpeg($sourFile); break; case 3: //png $img = imagecreatefrompng($sourFile); break; default: return 0; break; } if (!$img) { return 0; } $width = $this->maxWidth > $imageInfo["width"] ? $imageInfo["width"] : $this->maxWidth; $height = $this->maxHeight > $imageInfo["height"] ? $imageInfo["height"] : $this->maxHeight; $srcW = $imageInfo["width"]; $srcH = $imageInfo["height"]; if ($srcW * $width > $srcH * $height) { $height = round($srcH * $width / $srcW); } else { $width = round($srcW * $height / $srcH); } //* if (function_exists("imagecreatetruecolor")) { //GD2.0.1 $new = imagecreatetruecolor($width, $height); ImageCopyResampled($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); } else { $new = imagecreate($width, $height); ImageCopyResized($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); } $white = imageColorAllocate($new, 255, 255, 255); $black = imageColorAllocate($new, 0, 0, 0); $alpha = imageColorAllocateAlpha($new, 230, 230, 230, 40); //$rectW = max(strlen($text[0]),strlen($text[1]))*7; ImageFilledRectangle($new, 0, $height - 26, $width, $height, $alpha); ImageFilledRectangle($new, 13, $height - 20, 15, $height - 7, $black); ImageTTFText($new, 4.9, 0, 20, $height - 14, $black, $this->fontName, $text[0]); ImageTTFText($new, 4.9, 0, 20, $height - 6, $black, $this->fontName, $text[1]); //*/ if ($this->toFile) { if (file_exists($this->galleryPath . $newName)) { unlink($this->galleryPath . $newName); } ImageJPEG($new, $this->galleryPath . $newName); return $this->galleryPath . $newName; } else { ImageJPEG($new); } ImageDestroy($new); ImageDestroy($img); }
public function recover_image($id, $thumb_width, $thumb_height) { global $WD_BWG_UPLOAD_DIR; global $wpdb; $image_data = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'bwg_image WHERE id="%d"', $id)); $filename = htmlspecialchars_decode(ABSPATH . $WD_BWG_UPLOAD_DIR . $image_data->image_url, ENT_COMPAT | ENT_QUOTES); $thumb_filename = htmlspecialchars_decode(ABSPATH . $WD_BWG_UPLOAD_DIR . $image_data->thumb_url, ENT_COMPAT | ENT_QUOTES); if (file_exists($filename) && file_exists($thumb_filename)) { copy(str_replace('/thumb/', '/.original/', $thumb_filename), $filename); list($width_orig, $height_orig, $type_orig) = getimagesize($filename); $percent = $width_orig / $thumb_width; $thumb_height = $height_orig / $percent; @ini_set('memory_limit', '-1'); if ($type_orig == 2) { $img_r = imagecreatefromjpeg($filename); $dst_r = ImageCreateTrueColor($thumb_width, $thumb_height); imagecopyresampled($dst_r, $img_r, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig); imagejpeg($dst_r, $thumb_filename, 100); imagedestroy($img_r); imagedestroy($dst_r); } elseif ($type_orig == 3) { $img_r = imagecreatefrompng($filename); $dst_r = ImageCreateTrueColor($thumb_width, $thumb_height); imageColorAllocateAlpha($dst_r, 0, 0, 0, 127); imagealphablending($dst_r, FALSE); imagesavealpha($dst_r, TRUE); imagecopyresampled($dst_r, $img_r, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig); imagealphablending($dst_r, FALSE); imagesavealpha($dst_r, TRUE); imagepng($dst_r, $thumb_filename, 9); imagedestroy($img_r); imagedestroy($dst_r); } elseif ($type_orig == 1) { $img_r = imagecreatefromgif($filename); $dst_r = ImageCreateTrueColor($thumb_width, $thumb_height); imageColorAllocateAlpha($dst_r, 0, 0, 0, 127); imagealphablending($dst_r, FALSE); imagesavealpha($dst_r, TRUE); imagecopyresampled($dst_r, $img_r, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig); imagealphablending($dst_r, FALSE); imagesavealpha($dst_r, TRUE); imagegif($dst_r, $thumb_filename); imagedestroy($img_r); imagedestroy($dst_r); } @ini_restore('memory_limit'); } }
public function viewmergeimage() { $gotimages = $this->input->get_post("json"); // Get images from database $gotimages = json_decode($gotimages, TRUE); $frontfeatures = array(); $backfeatures = array(); //frontend img specifications $frontfeatures = $gotimages['custom']['4']; $backfeatures = $gotimages['custom']['5']; $newImagewidth = $frontfeatures['width'] * 5; $newImageheight = $frontfeatures['height'] * 5; $demofronttransparent = imagecreatetruecolor($newImagewidth, $newImageheight); imagesavealpha($demofronttransparent, true); $color = imagecolorallocatealpha($demofronttransparent, 0, 0, 0, 127); imagefill($demofronttransparent, 0, 0, $color); $phpfrontimg = imagecreatefrompng("./uploads/" . $gotimages['image']['image']); imagecopyresized($demofronttransparent, $phpfrontimg, 0, 0, 0, 0, $newImagewidth, $newImageheight, imagesx($phpfrontimg), imagesy($phpfrontimg)); // ROTATE IMAGE $rotate = imagerotate($demofronttransparent, 180, imageColorAllocateAlpha($demofronttransparent, 0, 0, 0, 127)); imagesavealpha($rotate, true); // create transparent layout $thumbfront = imagecreatetruecolor(194 * 5, 308 * 5); imagesavealpha($thumbfront, true); $color = imagecolorallocatealpha($thumbfront, 0, 0, 0, 127); imagefill($thumbfront, 0, 0, $color); // MERGE IMAGE imagecopyresized($thumbfront, $rotate, 10, 10, 0, 0, imagesx($rotate), imagesy($rotate), imagesx($rotate), imagesy($rotate)); imagesavealpha($thumbfront, true); header('Content-Type: image/png'); imagepng($thumbfront); }
function callCreateAlphaImageForDistorted() { // Example usage - gif image output $alphabet = $this->symbolsToUse; $alphabet = implode(" ", str_split($alphabet)); $text_string = $alphabet; $font_ttf = $this->font_ttf; $text_angle = 0; $text_padding = 20; // Img padding - around text $font_size = $this->font_size; $fontFileMeta = array('alphabet' => $alphabet, 'font_ttf' => basename($font_ttf), 'font_size' => $font_size); $fontMetaFile = $this->fontPNGLocation . $this->DS . $this->fontMetaFile; if (!file_exists($fontMetaFile)) { die("missing meta file : " . $fontMetaFile); } $savedfontMeta = unserialize(file_get_contents($fontMetaFile)); if (!is_array($savedfontMeta) || !isset($savedfontMeta['alphabet']) || !isset($savedfontMeta['font_ttf']) || !isset($savedfontMeta['font_size'])) { die("corrupted meta file : " . $fontMetaFile . " download the correct one "); } //die("Saved one <pre>".print_r(unserialize( file_get_contents($fontMetaFile)),true)."</pre><hr />Required one <pre>".print_r($fontFileMeta,true)."</pre>"); if ($savedfontMeta == $fontFileMeta) { return; } elseif (!(file_exists($font_ttf) || is_dir($font_ttf))) { $alphabet = $this->symbolsToUse = $savedfontMeta['alphabet']; $font_ttf = $this->font_ttf = $savedfontMeta['font_ttf']; $font_size = $this->font_size = $savedfontMeta['font_size']; } file_put_contents($fontMetaFile, serialize($fontFileMeta)); $the_box = $this->calculateTextBox($text_string, $font_ttf, $font_size, $text_angle); $imgWidth = $the_box["width"] + $text_padding * 2; $imgHeight = $the_box["height"] + $text_padding * 2; $img = $image = imagecreatetruecolor($imgWidth, $imgHeight); $colorBlack = imagecolorallocate($image, 0, 0, 0); imagealphablending($image, false); imagesavealpha($image, true); $transparent = imageColorAllocateAlpha($img, 0, 0, 0, 127); imagefilledrectangle($image, 0, 0, $imgWidth - 1, $imgHeight - 1, $transparent); imageAlphaBlending($image, true); imageantialias($image, true); imagettftext($image, $font_size, $text_angle, $the_box["left"] + $imgWidth / 2 - $the_box["width"] / 2, $the_box["top"] + $imgHeight / 2 - $the_box["height"] / 2, $colorBlack, $font_ttf, $text_string); imagealphablending($image, false); imagesavealpha($image, true); //header("content-type: image/png");imagepng($image);imagepng($image,'test.png');imagedestroy($image); exit; $font_file = $this->fontPNGLocation . $this->DS . $this->fontPNGFile; imagepng($image, $font_file); $image = $this->createAlphaImage(); imagepng($image, $font_file); }
function set_text_watermark($original_filename, $dest_filename, $watermark_text, $watermark_font, $watermark_font_size, $watermark_color, $watermark_transparency, $watermark_position) { $original_filename = htmlspecialchars_decode($original_filename, ENT_COMPAT | ENT_QUOTES); $dest_filename = htmlspecialchars_decode($dest_filename, ENT_COMPAT | ENT_QUOTES); $watermark_transparency = 127 - (100 - $watermark_transparency) * 1.27; list($width, $height, $type) = getimagesize($original_filename); $watermark_image = imagecreatetruecolor($width, $height); $watermark_color = $this->bwg_hex2rgb($watermark_color); $watermark_color = imagecolorallocatealpha($watermark_image, $watermark_color[0], $watermark_color[1], $watermark_color[2], $watermark_transparency); $watermark_font = WD_S_DIR . '/fonts/' . $watermark_font; $watermark_font_size = $height * $watermark_font_size / 500; $watermark_position = explode('-', $watermark_position); $watermark_sizes = $this->bwg_imagettfbboxdimensions($watermark_font_size, 0, $watermark_font, $watermark_text); $top = $height - 5; $left = $width - $watermark_sizes['width'] - 5; switch ($watermark_position[0]) { case 'top': $top = $watermark_sizes['height'] + 5; break; case 'middle': $top = ($height + $watermark_sizes['height']) / 2; break; } switch ($watermark_position[1]) { case 'left': $left = 5; break; case 'center': $left = ($width - $watermark_sizes['width']) / 2; break; } ini_set('memory_limit', '-1'); if ($type == 2) { $image = imagecreatefromjpeg($original_filename); imagettftext($image, $watermark_font_size, 0, $left, $top, $watermark_color, $watermark_font, $watermark_text); imagejpeg($image, $dest_filename, 100); imagedestroy($image); } elseif ($type == 3) { $image = imagecreatefrompng($original_filename); imagettftext($image, $watermark_font_size, 0, $left, $top, $watermark_color, $watermark_font, $watermark_text); imageColorAllocateAlpha($image, 0, 0, 0, 127); imagealphablending($image, FALSE); imagesavealpha($image, TRUE); imagepng($image, $dest_filename, 9); imagedestroy($image); } elseif ($type == 1) { $image = imagecreatefromgif($original_filename); imageColorAllocateAlpha($watermark_image, 0, 0, 0, 127); imagecopy($watermark_image, $image, 0, 0, 0, 0, $width, $height); imagettftext($watermark_image, $watermark_font_size, 0, $left, $top, $watermark_color, $watermark_font, $watermark_text); imagealphablending($watermark_image, FALSE); imagesavealpha($watermark_image, TRUE); imagegif($watermark_image, $dest_filename); imagedestroy($image); } imagedestroy($watermark_image); ini_restore('memory_limit'); }
/** * @param $angle * @return $this|self */ public function rotate($angle) { $this->preModify(); $angle = 360 - $angle; $this->resource = imagerotate($this->resource, $angle, imageColorAllocateAlpha($this->resource, 0, 0, 0, 127)); $this->setWidth(imagesx($this->resource)); $this->setHeight(imagesy($this->resource)); $this->postModify(); $this->setIsAlphaPossible(true); return $this; }
<?php $im = imageCreateTrueColor(110, 30); $color = imageColorAllocate($im, 255, 198, 0); imageAntiAlias($im, true); imageFill($im, 10, 10, $color); //добавлеяем фоновые точки на картинке $color = imageColorAllocateAlpha($im, 116, 187, 15, 50); for ($i = 0; $i < 800; $i++) { $randW = mt_rand(0, imageSX($im)); $randH = mt_rand(0, imageSY($im)); imageSetPixel($im, $randW, $randH, $color); } //создаем массив значений букв и цыфр для капчи $color = imageColorAllocate($im, 255, 255, 255); $letters = array_merge(range('A', 'Z'), range(0, 9)); //составляем и удаляем лишние символы, которые приводят к путанице $delLetters = ['O', 'I', 'J', 7, '0', 'Q', '5', 'S']; for ($i = 0; $i < count($delLetters); $i++) { unset($letters[array_search($delLetters[$i], $letters)]); } //перемешиваем массив и выбираем срез shuffle($letters); $sliceLetters = array_slice($letters, 0, 5); //устанавливаем настройки для отображения символов и выводим текст $deg = [10, -10, 15, 0, -20]; $rands = [mt_rand(0, 7), mt_rand(0, 9), mt_rand(8, 15), mt_rand(0, 9), mt_rand(16, 23)]; $opts = [mt_rand(2, 8), mt_rand(22, 26), mt_rand(46, 50), mt_rand(70, 72), mt_rand(86, 88)]; for ($i = 0; $i < count($sliceLetters); $i++) { $letter = $sliceLetters[$i]; $str .= $letter;
<?php ## Работа с полупрозрачными цветами. $size = 300; $im = imageCreateTrueColor($size, $size); $back = imageColorAllocate($im, 255, 255, 255); imageFilledRectangle($im, 0, 0, $size - 1, $size - 1, $back); // Создаем идентификаторы полупрозрачных цветов. $yellow = imageColorAllocateAlpha($im, 255, 255, 0, 75); $red = imageColorAllocateAlpha($im, 255, 0, 0, 75); $blue = imageColorAllocateAlpha($im, 0, 0, 255, 75); // Рисуем 3 пересекающихся круга. $radius = 150; imageFilledEllipse($im, 100, 75, $radius, $radius, $yellow); imageFilledEllipse($im, 120, 165, $radius, $radius, $red); imageFilledEllipse($im, 187, 125, $radius, $radius, $blue); // Выводим изображение в браузер. header('Content-type: image/png'); imagePng($im);
/** * 给图片加水印 * @author 肖飞(原作者),嬴益虎(2010-2-1修改) * @param string $sourFile 图片文件名 * @param boolean $isSmall 是否缩略图打水印 * @param boolean $toFile 是否覆盖原文件 * @return 1 成功 成功时返回生成的图片路径 */ function waterMark($sourFile, $isSmall = false, $toFile = true) { global $arrGWeb; $arrGPicWater = $arrGWeb; if ($isSmall) { return 0; } //保留这个,是为了以后,如果有需要,针对biweb缩略图的扩展处理 $imageInfo = $this->getInfo($sourFile); $text = array("biweb.cn", "all rights reserved"); //如果水印内容设置为空,默认用此设置 $this->fontName = __WEBCOMMON_ROOT . '/04B_08__.TTF'; switch ($imageInfo["type"]) { case 1: //gif $img = imagecreatefromgif($sourFile); break; case 2: //jpg $img = imagecreatefromjpeg($sourFile); break; case 3: //png $img = imagecreatefrompng($sourFile); break; default: return 0; break; } if (!$img) { return 0; } $width = $this->maxWidth > $imageInfo["width"] ? $imageInfo["width"] : $this->maxWidth; $height = $this->maxHeight > $imageInfo["height"] ? $imageInfo["height"] : $this->maxHeight; $srcW = $imageInfo["width"]; $srcH = $imageInfo["height"]; if ($srcW * $width > $srcH * $height) { $height = round($srcH * $width / $srcW); } else { $width = round($srcW * $height / $srcH); } //* if (function_exists("imagecreatetruecolor")) { //GD2.0.1 $new = imagecreatetruecolor($width, $height); ImageCopyResampled($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); } else { $new = imagecreate($width, $height); ImageCopyResized($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); } $white = imageColorAllocate($new, 255, 255, 255); $black = imageColorAllocate($new, 0, 0, 0); $red = imageColorAllocate($new, 255, 0, 0); $alpha = imageColorAllocateAlpha($new, 230, 230, 230, 40); //================================================================ if (!empty($arrGPicWater['bgColor'])) { $intTemp = explode(',', $arrGPicWater['bgColor']); $bgColor = imageColorAllocateAlpha($new, $intTemp['0'], $intTemp['1'], $intTemp['2'], $intTemp['3']); } else { $bgColor = $alpha; } if (!empty($arrGPicWater['fgColor'])) { $intTemp = explode(',', $arrGPicWater['fgColor']); $fgColor = imageColorAllocate($new, $intTemp['0'], $intTemp['1'], $intTemp['2']); } else { $fgColor = $black; } if (!empty($arrGPicWater['navColor'])) { $intTemp = explode(',', $arrGPicWater['navColor']); $navColor = imageColorAllocate($new, $intTemp['0'], $intTemp['1'], $intTemp['2']); } else { $navColor = $black; } if (!empty($arrGPicWater['text0']) && !empty($arrGPicWater['text1'])) { $text[0] = $arrGPicWater['text0']; $text[1] = $arrGPicWater['text1']; } if (!$isSmall) { if (!empty($arrGPicWater['width'])) { $width = $arrGPicWater['width']; } if (!empty($arrGPicWater['height'])) { $height = $arrGPicWater['height']; } $x = 0; $y = 0; $fontSize = 4.9; if (!empty($arrGPicWater['xPic'])) { $x = $arrGPicWater['xPic']; } if (!empty($arrGPicWater['yPic'])) { $y = $arrGPicWater['yPic']; } if (!empty($arrGPicWater['fontsize'])) { $fontSize = $arrGPicWater['fontsize']; } if ($x + $width > $imageInfo['width']) { $x = $imageInfo['width'] - $width; } if ($y + $height > $imageInfo['height']) { $y = $imageInfo['height'] - $height; } } //================================================================ //$rectW = max(strlen($text[0]),strlen($text[1]))*7; ImageFilledRectangle($new, 0 + $x, $height - 26 + $y, $width + $x, $height + $y, $bgColor); ImageFilledRectangle($new, 13 + $x, $height - 20 + $y, 15 + $x, $height - 7 + $y, $navColor); ImageTTFText($new, $fontSize, 0, 20 + $x, $height - 14 + $y, $fgColor, $this->fontName, $text[0]); ImageTTFText($new, $fontSize, 0, 20 + $x, $height - 2 + $y, $fgColor, $this->fontName, $text[1]); //*/ if ($toFile) { if (file_exists($sourFile)) { unlink($sourFile); } ImageJPEG($new, $sourFile); } else { ImageJPEG($new); } ImageDestroy($new); ImageDestroy($img); }
// Getting all image sizes $sizes = ['x' => [], 'y' => []]; foreach ($files as $k => $file) { $size = getImageSize($file); $sizes['x'][$k] = $size[0]; $sizes['y'][$k] = $size[1]; } // Getting tile and canvas sizes $tile_size = ['x' => max($sizes['x']), 'y' => max($sizes['y'])]; $canvas_size = ceil(sqrt($count)); $canvas_size = ['x' => $canvas_size * $tile_size['x'], 'y' => $canvas_size * $tile_size['y']]; // Creating the canvas $canvas = imageCreateTrueColor($canvas_size['x'], $canvas_size['y']); // Making it transparent imageAlphaBlending($canvas, false); imageFill($canvas, 0, 0, imageColorAllocateAlpha($canvas, 0, 0, 0, 127)); imageSaveAlpha($canvas, true); // Initializing the CSS array $css = []; // Setting the image input function (it depends on the format) $imageCreateFrom = 'imageCreateFrom' . $input_extension; // Setting the 2D pointer to its initial position $pointer = ['x' => 0, 'y' => 0]; foreach ($files as $id => $file) { // Getting image $image = call_user_func($imageCreateFrom, $file); // Copying image into the canvas imageCopy($canvas, $image, $pointer['x'], $pointer['y'], 0, 0, $sizes['x'][$id], $sizes['y'][$id]); // Destroying image imageDestroy($image); // Adding coordinates to the CSS array
/** * rotate image * @param integer|string $degree degree of rotation. (0, 90, 180, 270). for php < 5.5, you cannot use flip hor, vrt, horvrt * @return boolean */ public function rotate($degree = '90') { // if constructor failed to load. if (!$this->checkConstructorLoad()) { return false; } // check degree $allowed_degree = array(0, 90, 180, 270, 'hor', 'vrt', 'horvrt'); if (!in_array($degree, $allowed_degree)) { $degree = 90; } if (!is_int($degree) && $degree != 'hor' && $degree != 'vrt' && $degree != 'horvrt') { $degree = (int) $degree; } unset($allowed_degree); // if image content not set, set it up (this case just call crop without resize). if ($this->new_img_content == null) { $result = $this->setImageContent(); if ($result === false) { $this->status = false; $this->status_msg = 'Failed to set image content.'; return false; } $new_img_content = $this->new_img_content; unset($result); } else { $new_img_content = $this->new_img_object; } // rotate. if (is_int($degree)) { // rotate by degrees number switch ($this->original_img_ext) { case '1': // gif // gif case '2': // jpg $rotate = imagerotate($new_img_content, $degree, 0); break; case '3': // png $rotate = imagerotate($new_img_content, $degree, imageColorAllocateAlpha($new_img_content, 0, 0, 0, 127)); imagealphablending($rotate, false); imagesavealpha($rotate, true); break; default: // not allowed image type. $this->status = false; $this->status_msg = 'Unable to rotate this type of image.'; return false; break; } $this->new_img_object = $rotate; $this->new_img_height = imagesy($rotate); $this->new_img_width = imagesx($rotate); // re-set original image height & width. because image was rotate $this->original_img_height = $this->new_img_height; $this->original_img_width = $this->new_img_width; } else { // if php version lower than 5.5 if (phpversion() < 5.5) { $this->status = false; $this->status_msg = 'Unable to flip image using PHP older than 5.5.'; return false; } if ($degree == 'hor') { $mode = IMG_FLIP_HORIZONTAL; } elseif ($degree == 'vrt') { $mode = IMG_FLIP_VERTICAL; } else { $mode = IMG_FLIP_BOTH; } // flip image. imageflip($new_img_content, $mode); unset($mode); $this->new_img_object = $new_img_content; $this->new_img_height = imagesy($new_img_content); $this->new_img_width = imagesx($new_img_content); // re-set original image height & width. because image was rotate $this->original_img_height = $this->new_img_height; $this->original_img_width = $this->new_img_width; } return true; }
/** * {@inheritDoc} */ public function rotate($degree = 90) { if (false === $this->isClassSetup()) { return false; } // check degree $allowed_flip = array('hor', 'vrt', 'horvrt'); if (is_numeric($degree)) { $degree = intval($degree); } elseif (!is_numeric($degree) && !in_array($degree, $allowed_flip)) { $degree = 90; } unset($allowed_flip); // setup source image object if (false === $this->setupSourceImageObject()) { return false; } // check previous step contain errors? if ($this->isPreviousError() === true) { return false; } // begins rotate. if (is_int($degree)) { // rotate by degree switch ($this->source_image_type) { case '1': // gif // set source image width and height $source_image_width = imagesx($this->source_image_object); $source_image_height = imagesy($this->source_image_object); $this->destination_image_object = imagecreatetruecolor($source_image_width, $source_image_height); $transwhite = imagecolorallocatealpha($this->destination_image_object, 255, 255, 255, 127); imagefill($this->destination_image_object, 0, 0, $transwhite); imagecolortransparent($this->destination_image_object, $transwhite); imagecopy($this->destination_image_object, $this->source_image_object, 0, 0, 0, 0, $source_image_width, $source_image_height); $this->destination_image_object = imagerotate($this->destination_image_object, $degree, $transwhite); unset($source_image_height, $source_image_width, $transwhite); break; case '2': // jpg $white = imagecolorallocate($this->source_image_object, 255, 255, 255); $this->destination_image_object = imagerotate($this->source_image_object, $degree, $white); unset($white); break; case '3': // png $transwhite = imageColorAllocateAlpha($this->source_image_object, 0, 0, 0, 127); $this->destination_image_object = imagerotate($this->source_image_object, $degree, $transwhite); imagealphablending($this->destination_image_object, false); imagesavealpha($this->destination_image_object, true); unset($transwhite); break; default: $this->status = false; $this->status_msg = 'Unable to rotate this kind of image.'; return false; } $this->destination_image_height = imagesy($this->destination_image_object); $this->destination_image_width = imagesx($this->destination_image_object); $this->source_image_height = $this->destination_image_height; $this->source_image_width = $this->destination_image_width; } else { // flip image if (version_compare(phpversion(), '5.5', '<')) { $this->status = false; $this->status_msg = 'Unable to flip image using PHP older than 5.5.'; return false; } if ($degree == 'hor') { $mode = IMG_FLIP_HORIZONTAL; } elseif ($degree == 'vrt') { $mode = IMG_FLIP_VERTICAL; } else { $mode = IMG_FLIP_BOTH; } // flip image. imageflip($this->source_image_object, $mode); unset($mode); $this->destination_image_object = $this->source_image_object; $this->destination_image_height = imagesy($this->source_image_object); $this->destination_image_width = imagesx($this->source_image_object); $this->source_image_height = $this->destination_image_height; $this->source_image_width = $this->destination_image_width; } // clear if (get_resource_type($this->source_image_object) === 'gd') { if ($this->source_image_object != $this->destination_image_object) { imagedestroy($this->source_image_object); } $this->source_image_object = null; } if (!$this->isPreviousError()) { $this->status = true; $this->status_msg = null; } return true; }
function bwg_image_flip($imgsrc, $mode) { $width = imagesx($imgsrc); $height = imagesy($imgsrc); $src_x = 0; $src_y = 0; $src_width = $width; $src_height = $height; switch ($mode) { case 'vertical': $src_y = $height - 1; $src_height = -$height; break; case 'horizontal': $src_x = $width - 1; $src_width = -$width; break; case 'both': $src_x = $width - 1; $src_y = $height - 1; $src_width = -$width; $src_height = -$height; break; default: return $imgsrc; } $trans_colour = imageColorAllocateAlpha($imgsrc, 0, 0, 0, 127); $imgdest = imagecreatetruecolor($width, $height); imagefill($imgdest, 0, 0, $trans_colour); if (imagecopyresampled($imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height)) { return $imgdest; } return $imgsrc; }
public function create($text, $font = null, $material = null, $options = null) { if (!empty($text)) { $this->setText($text); } if (!empty($font)) { $this->setFont($font); } if (!$this->orderData instanceof \Zivsluck\Entity\Laravel\Order && !empty($options['oid'])) { $orderData = zbase_entity('custom_orders')->repository()->byId($options['oid']); if (empty($orderData)) { return zbase_abort(404); } $this->setOrderData($orderData); } $tags = []; $dealerCopy = !empty($options['dealerCopy']) ? true : false; /** * <span id="IL_AD8" class="IL_AD">Setup</span> some custom variables for creating our font and image. */ $chain = !empty($options['chain']) ? $options['chain'] : false; $chainLength = !empty($options['chainLength']) ? $options['chainLength'] : false; $maxLetter = 7; $pricePerLetter = 20; $boxWidth = 280; $boxHeight = 200; $brandingHeightPosition = 200; $borderWidth = 10; $hasBorder = !empty($dealerCopy) ? true : false; $hasDetails = false; $fontsNotForMaterial = zbase_config_get('zivsluck.chains.' . $material . '.fonts.not', []); $fontNotForMaterial = false; $posYDiff = 0; if (!empty($fontsNotForMaterial)) { if (in_array($font, $fontsNotForMaterial)) { $fontNotForMaterial = true; } } if (!empty($chain) && !empty($chainLength)) { $hasDetails = true; $boxWidth = 280; $boxHeight = 600; $brandingHeightPosition = 600; $chainFile = zbase_config_get('zivsluck.chains.' . strtolower($material) . '.' . strtolower($chain) . '.file', false); $chainImage = zbase_public_path() . '/zbase/assets/zivsluck/img/chain/' . $chainFile; $tags[] = $chain; } $letterPrice = 0; $shippingFee = 0; $hasShipping = false; $total = 0; $courier = !empty($options['courier']) ? $options['courier'] : false; if (!empty($courier)) { $courier = zbase_config_get('zivsluck.shipping.' . strtolower($courier), false); if (!empty($courier)) { $deliveryMode = !empty($options['deliveryMode']) ? $options['deliveryMode'] : false; $hasShipping = true; $courierName = $courier['name']; if ($deliveryMode == 'meetup') { $courierText = 'Meet Up'; $shippingFee = 0.0; } else { $shippingFee = $courier['fee']; $courierText = $courierName . ' - ' . ($deliveryMode == 'doortodoor' ? 'Door-to-Door' : 'PickUp'); } $boxWidth = 280; $boxHeight = 800; $brandingHeightPosition = 800; } if (empty($options['shippingSame'])) { $options['shippingFirstName'] = $options['first_name']; $options['shippingLastName'] = $options['last_name']; } } $customerNote = !empty($options['customerNote']) ? $options['customerNote'] : ''; $orderData = $this->getOrderData(); $statusNew = false; $statusPaid = false; if (!empty($orderData)) { $statusPaid = $orderData->status == 2; if (!empty($options['download']) && $orderData->status == 1) { $boxWidth = 280; $boxHeight = 800 + 380; $posYDiff = 190; $brandingHeightPosition = 800; $statusNew = true; } if (!empty($statusPaid)) { $paymentCenterName = zbase_config_get('zivsluck.paymentCenters.' . $orderData->payment_merchant . '.shortName'); $paymentAmount = $orderData->total; if (file_exists(zbase_storage_path() . '/zivsluck/order/receipts/' . $orderData->maskedId() . '.png')) { $paymentDetailsIm = imagecreatefrompng(zbase_storage_path() . '/zivsluck/order/receipts/' . $orderData->maskedId() . '.png'); $boxHeight = $boxHeight + imagesy($paymentDetailsIm); $posYDiff = imagesy($paymentDetailsIm) / 2; $brandingHeightPosition = 800; } } } $price = zbase_config_get('zivsluck.price.' . $material, false); $fontSize = 30; // font size $chars = 30; $fontFile = zbase_public_path() . '/zbase/assets/zivsluck/fonts/deftonestylus.ttf'; // the text file to be used $verdanaFont = zbase_public_path() . '/zbase/assets/zivsluck/fonts/verdana.ttf'; // the text file to be used $textureFile = zivsluck()->path() . 'resources/assets/img/texture/' . strtolower($material) . '.png'; // the texture file $logo = zivsluck()->path() . 'resources/assets/img/texture/logo.png'; // the texture file $paymentDetails = zivsluck()->path() . 'resources/assets/img/payments/bayadCenter.png'; // the texture file $fontDetails = $this->getFontDetails(); $tags[] = $material; $tags[] = $font; if (!empty($dealerCopy)) { $boxWidth = 280; $boxHeight = 500; $brandingHeightPosition = 500; $posYDiff = 0; } /** * Get text string that is <span id="IL_AD7" class="IL_AD">passed</span> to this file and clean it up. */ $text = $this->getText(); $text = trim(strip_tags(html_entity_decode($text))); // $text = trim(preg_replace('/ss+/', ' ', $text)); $text = strlen($text) > $chars ? substr($text, 0, $chars) . '..' : $text; if (!empty($fontDetails['enable'])) { $fontFile = zbase_public_path() . '/zbase/assets/zivsluck/fonts/' . $fontDetails['file']; if (!empty($fontDetails['fontsize'])) { $fontSize = $fontDetails['fontsize']; } } else { $fontFile = $verdanaFont; $text = 'FONT NOT AVAILABLE.'; } if ($fontNotForMaterial) { $fontFile = $verdanaFont; $fontSize = 14; // font size $text = wordwrap("ERROR: \nFONT NOT FOR " . strtoupper($material) . ". \nSelect another font.", 20); $hasDetails = false; $boxWidth = 280; $boxHeight = 200; $brandingHeightPosition = 200; } // <editor-fold defaultstate="collapsed" desc="Image Printin"> /** * Read the TTF file and get the width and height of our font. */ $box = imagettfbbox($fontSize, 0, $fontFile, $text); $width = abs($box[2] - $box[0]) + 50; /** * Create <span id="IL_AD2" class="IL_AD">the blank</span> image, alpha channel and colors. */ // http://stackoverflow.com/questions/26288347/php-gd-complex-stacking-multiple-layers // $clipart = imagecreatefrompng(zivsluck()->path() . 'resources/assets/img/createBaseImage.png'); $bgTexture = imagecreatefrompng($textureFile); $noBg = !empty(zbase_cookie('nobg')) ? true : false; $logo = imagecreatefrompng($logo); $white = imagecolorallocate($bgTexture, 255, 255, 255); if ($dealerCopy) { // Canvass $bgTexture = imagecreatetruecolor($boxWidth - $borderWidth * 2, $boxHeight - $borderWidth * 2); // Background Color $white = imagecolorallocate($bgTexture, 255, 255, 255); } if (!empty($noBg)) { $bgTexture = imagecreatetruecolor($boxWidth, $boxHeight); } /** * Create text on a white background */ imagefill($bgTexture, 0, 0, $white); $textColorBlack = imagecolorallocate($bgTexture, 0, 0, 0); if (empty($posY)) { if ($hasDetails) { if ($hasShipping) { $posY = $boxHeight / 2 + 10 - 300 - $posYDiff; } else { $posY = $boxHeight / 2 + 10 - 200 - $posYDiff; } } else { $posY = $boxHeight / 2 + 10 - $posYDiff; } $posX = $boxWidth / 2 - $width / 2 + 10; if (!empty($hasBorder)) { $posY = $boxHeight / 2 + 10 - 150 - $borderWidth - $posYDiff; $posX = $boxWidth / 2 - $width / 2; } } if ($fontNotForMaterial) { imagettftext($bgTexture, $fontSize, 0, $posX, 60, $textColorBlack, $fontFile, $text); } else { imagettftext($bgTexture, $fontSize, 0, $posX, $posY, $textColorBlack, $fontFile, $text); } $im = imagecreatetruecolor($boxWidth, $boxHeight); if (!empty($dealerCopy)) { imagecopy($im, $bgTexture, $borderWidth, $borderWidth, 0, 0, $boxWidth, $boxHeight); } else { imagecopy($im, $bgTexture, 0, 0, 0, 0, $boxWidth, $boxHeight); } $img = imagecreatetruecolor($boxWidth, $boxHeight); imagecopymerge($img, $im, 0, 0, 0, 0, $boxWidth, $boxHeight, 100); if ($hasBorder) { imagecopy($img, $logo, 234, $brandingHeightPosition - 45, 0, 0, imagesx($logo), imagesy($logo)); } else { imagecopy($img, $logo, 245, $brandingHeightPosition - 35, 0, 0, $boxWidth, $boxHeight); } if (!empty($dealerCopy)) { // Add border imagefilltoborder($img, 1, 1, $textColorBlack, $white); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="ADDON"> $totalAddon = 0; if (!empty($options['addon'])) { $addonDroppableTop = zbase_config_get('zivsluck.addons.configuration.droppable.top') - 5; $addonDroppableLeft = zbase_config_get('zivsluck.addons.configuration.droppable.left') - 5; $addonDroppableHeight = zbase_config_get('zivsluck.addons.configuration.droppable.height'); $addonDroppableWidth = zbase_config_get('zivsluck.addons.configuration.droppable.width'); $addons = explode('|', $options['addon']); $includedAddons = []; foreach ($addons as $addon) { if (!empty($addon)) { // $addon = explode('-', $addon); // $addonName = !empty($addon[0]) ? $addon[0] : false; // $addonEnabled = zbase_config_get('zivsluck.addons.' . $addonName . '.enable'); // $addonFile = zivsluck()->path() . 'resources/assets/img/addons/' . zbase_config_get('zivsluck.addons.' . $addonName . '.file'); // $addonPosition = !empty($addon[1]) ? explode(',', $addon[1]) : false; // $addonSize = !empty($addon[2]) ? explode('x', $addon[2]) : false; // $addonRotate = intval(!empty($addon[3]) ? $addon[3] : false); $addon = explode('-', $addon); $addonName = !empty($addon[0]) ? $addon[0] : false; $addonEnabled = true; //zbase_config_get('zivsluck.addons.' . $addonName . '.enable'); $addonFile = zivsluck()->path() . 'resources/assets/img/addons/' . $addonName . '.png'; $addonPosition = !empty($addon[1]) ? explode(',', $addon[1]) : false; $addonSize = !empty($addon[2]) ? explode('x', $addon[2]) : false; $addonRotate = intval(!empty($addon[3]) ? $addon[3] : false); if (!empty($addonEnabled) && file_exists($addonFile)) { if (!in_array($addonName, $tags)) { $tags[] = $addonName; } $includedAddons[] = $addonName; $addonNewImage = imagecreatetruecolor($addonSize[0], $addonSize[1]); $transparent = imagecolorallocatealpha($addonNewImage, 0, 0, 0, 127); $addonFile = imagecreatefrompng($addonFile); if (!empty($addonRotate)) { $addonFile = imagerotate($addonFile, 360 - $addonRotate, imageColorAllocateAlpha($addonFile, 0, 0, 0, 127)); } if (empty($addonSize[0])) { $addonSize[0] = imagesx($addonFile); } if (empty($addonSize[1])) { $addonSize[1] = imagesy($addonFile); } imagefill($addonNewImage, 0, 0, $transparent); imagecopyresampled($addonNewImage, $addonFile, 0, 0, 0, 0, $addonSize[0], $addonSize[1], imagesx($addonFile), imagesy($addonFile)); $totalAddon++; imagecopy($img, $addonNewImage, $addonPosition[0] + $addonDroppableLeft, $addonPosition[1] + $addonDroppableTop, 0, 0, $addonSize[0], $addonSize[1]); } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Checkout Details"> if ($hasDetails) { // <editor-fold defaultstate="collapsed" desc="DISCOUNT"> $discountInPrice = zbase_config_get('zivsluck.promotion.discount', 0.0); if (!empty($orderData) && !empty($options['final'])) { $promo = !empty($options['promo_flag']) ? true : false; if (!empty($promo)) { $discountInPrice = $options['promo_discountprice']; $shippingFee = $options['promo_shipping_fee']; $associateOrderId = $options['promo_associate_order_id']; } else { if (!empty($options['promo_associate_order_id'])) { $associateOrderId = $options['promo_associate_order_id']; } } } else { $promo = $this->_discountOnNextOrder($text, $font, $material, $options); $options['promo_flag'] = 0; if (!empty($promo)) { $promoOrder = $promo; $promo = true; $options['promo_flag'] = 1; $shippingFee = 0.0; $options['promo_discountprice'] = $discountInPrice; $options['promo_shipping_fee'] = $shippingFee; $options['promo_associate_order_id'] = $promoOrder->id(); $associateOrderId = $promoOrder->id(); } } // </editor-fold> if (empty($dealerCopy)) { $chainImage = imagecreatefrompng($chainImage); $total = $price; $subTotal = $price; $letterCount = strlen($text); $addonPrice = 0; $totalCharacters = $letterCount + $totalAddon; if ($totalCharacters > $maxLetter) { if ($letterCount > $maxLetter) { if (!empty($totalAddon)) { $addonCount = $letterCount + $totalAddon - $maxLetter; $addonPrice = $addonCount * 20; $total += $addonPrice; $subTotal += $addonPrice; } } else { $totalAddon = $totalCharacters - $maxLetter; $addonPrice = $totalAddon * 20; } } // if($letterCount < $maxLetter) // { // if(!empty($totalAddon)) // { // $addonCount = ($letterCount + $totalAddon) - $maxLetter; // $addonPrice = $addonCount * 20; // $total += $addonPrice; // $subTotal += $addonPrice; // } // } // if($letterCount > $maxLetter) // { // $letterPrice = ($letterCount - $maxLetter) * 20; // $total += $letterPrice; // $addonPrice = $totalAddon * 20; // $total += $addonPrice; // $subTotal += $addonPrice; // } $total += $shippingFee; if (!empty($promo)) { $total -= $discountInPrice; } if (!empty($orderData)) { imagettftext($img, 12, 0, 15, 180, $textColorBlack, $verdanaFont, 'ORDER ID: ' . $orderData->maskedId()); } imagecopy($img, $chainImage, 15, 295, 0, 0, imagesx($chainImage), imagesy($chainImage)); } if (!empty($dealerCopy)) { imagettftext($img, 9, 0, 25, 200, $textColorBlack, $verdanaFont, 'Text: ' . $text); imagettftext($img, 9, 0, 25, 220, $textColorBlack, $verdanaFont, 'Font: ' . $fontDetails['name']); imagettftext($img, 9, 0, 25, 240, $textColorBlack, $verdanaFont, 'Material: ' . ucfirst($material)); imagettftext($img, 9, 0, 25, 260, $textColorBlack, $verdanaFont, 'Chain: ' . strtoupper($chain)); imagettftext($img, 9, 0, 25, 280, $textColorBlack, $verdanaFont, 'Chain Length: ' . $chainLength . '"'); if (!empty($includedAddons)) { imagettftext($img, 8, 0, 25, 300, $textColorBlack, $verdanaFont, 'Included Addons:'); imagettftext($img, 8, 0, 25, 320, $textColorBlack, $verdanaFont, wordwrap(implode(', ', $includedAddons), 30)); } if (!empty($customerNote)) { imagettftext($img, 9, 0, 25, 360, $textColorBlack, $verdanaFont, 'Customer Note:'); imagettftext($img, 8, 0, 25, 380, $textColorBlack, $verdanaFont, wordwrap($customerNote, 40)); } } else { imagettftext($img, 9, 0, 15, 200, $textColorBlack, $verdanaFont, 'Text: ' . $text); imagettftext($img, 9, 0, 15, 215, $textColorBlack, $verdanaFont, 'Font: ' . $fontDetails['name']); imagettftext($img, 9, 0, 15, 230, $textColorBlack, $verdanaFont, 'Character: ' . strlen($text)); imagettftext($img, 9, 0, 15, 245, $textColorBlack, $verdanaFont, 'Symbols: ' . $totalAddon); imagettftext($img, 9, 0, 15, 260, $textColorBlack, $verdanaFont, 'Material: ' . ucfirst($material)); imagettftext($img, 9, 0, 15, 275, $textColorBlack, $verdanaFont, 'Chain Length: ' . $chainLength . '"'); imagettftext($img, 9, 0, 15, 290, $textColorBlack, $verdanaFont, 'Chain: ' . strtoupper($chain)); if (!empty($this->displayPrice)) { imagettftext($img, 9, 0, 15, 430, $textColorBlack, $verdanaFont, ucfirst($material) . ' Price: Php ' . number_format($price, 2)); imagettftext($img, 9, 0, 15, 445, $textColorBlack, $verdanaFont, 'Characters: Php ' . number_format($letterPrice, 2)); imagettftext($img, 9, 0, 15, 460, $textColorBlack, $verdanaFont, 'Symbols: Php ' . number_format($addonPrice, 2)); } if ($hasShipping) { imagettftext($img, 9, 0, 15, 475, $textColorBlack, $verdanaFont, 'Shipping: Php ' . number_format($shippingFee, 2)); imagettftext($img, 9, 0, 15, 490, $textColorBlack, $verdanaFont, 'Courier: ' . $courierText); if (!empty($promo)) { imagettftext($img, 9, 0, 15, 505, $textColorBlack, $verdanaFont, 'Discount: ' . number_format($discountInPrice, 2) . ' (Order#' . $associateOrderId . ')'); } else { if (!empty($associateOrderId)) { imagettftext($img, 9, 0, 15, 505, $textColorBlack, $verdanaFont, 'Associate Order Id: ' . $associateOrderId); } } imagettftext($img, 9, 0, 15, 580, $textColorBlack, $verdanaFont, 'Shipping Information:'); imagettftext($img, 9, 0, 15, 600, $textColorBlack, $verdanaFont, $options['shippingFirstName'] . ' ' . $options['shippingLastName']); imagettftext($img, 9, 0, 15, 615, $textColorBlack, $verdanaFont, $options['address']); imagettftext($img, 9, 0, 15, 630, $textColorBlack, $verdanaFont, $options['addressb']); imagettftext($img, 9, 0, 15, 645, $textColorBlack, $verdanaFont, $options['city']); imagettftext($img, 8, 0, 15, 665, $textColorBlack, $verdanaFont, 'Ordered By: ' . $options['first_name'] . ' ' . $options['last_name']); imagettftext($img, 8, 0, 15, 680, $textColorBlack, $verdanaFont, $options['fb']); imagettftext($img, 8, 0, 15, 695, $textColorBlack, $verdanaFont, 'Phone: ' . $options['phone']); if (!empty($options['email'])) { imagettftext($img, 8, 0, 15, 710, $textColorBlack, $verdanaFont, 'Email: ' . $options['email']); } if (!empty($options['oid'])) { imagettftext($img, 8, 0, 15, 748, $textColorBlack, $verdanaFont, 'Order Link: ' . zbase_url_create('order', array('id' => $options['oid']))); } imagettftext($img, 8, 0, 15, 760, $textColorBlack, $verdanaFont, 'Date: ' . date('F d, Y h:i A')); } if (!empty($this->displayPrice)) { imagettftext($img, 18, 0, 15, 540, $textColorBlack, $verdanaFont, 'Total: Php ' . number_format($total, 2)); } if (!empty($statusPaid)) { imagettftext($img, 9, 0, 15, 555, $textColorBlack, $verdanaFont, 'PAID ' . number_format($paymentAmount, 2) . ' via ' . $paymentCenterName . ' (' . $orderData->paid_date_at->format('m/d/Y') . ')'); } if (!empty($orderData) && $orderData->status == 1 && !empty($options['step']) && $options['step'] == 5) { $orderData->total = $total; $orderData->subtotal = $subTotal; $orderData->shipping_fee = $shippingFee; unset($options['step']); $options['final'] = 1; if (!empty($promoOrder)) { $orderData->promo_flag = 1; } $orderData->details = json_encode($options); if (!empty($tags)) { $orderData->tags = implode(', ', $tags); } $orderData->save(); if (!empty($promoOrder)) { $promoOrderDetails = (array) $promoOrder->details(); $promoOrderDetails['promo_associate_order_id'] = $orderData->id(); $promoOrder->details = json_encode($promoOrderDetails); $promoOrder->promo_flag = 1; $promoOrder->save(); } } } } else { imagettftext($img, 9, 0, 15, 23, $textColorBlack, $verdanaFont, 'Font: ' . $fontDetails['name']); } if (!empty($hasBorder)) { imagettftext($img, 7, 0, 15, $brandingHeightPosition - (10 + $borderWidth), $textColorBlack, $verdanaFont, 'Create your necklace at http://zivsluck.com'); } else { imagettftext($img, 7, 0, 15, $brandingHeightPosition - 10, $textColorBlack, $verdanaFont, 'Create your necklace at http://zivsluck.com'); } if (!empty($statusNew)) { $paymentDetailsIm = imagecreatefrompng($paymentDetails); imagecopy($img, $paymentDetailsIm, 0, 800, 0, 0, $boxWidth, $boxHeight); } if (!empty($statusPaid) && empty($dealerCopy)) { if (!empty($paymentDetailsIm)) { imagecopy($img, $paymentDetailsIm, 0, 800, 0, 0, $boxWidth, $boxHeight); } } // </editor-fold> /** * Label */ $this->_image = $img; return $this; }
/** * Method to resize the current image. * * @param mixed $width The width of the resized image in pixels or a percentage. * @param mixed $height The height of the resized image in pixels or a percentage. * @param boolean $createNew If true the current image will be cloned, resized and returned; else * the current image will be resized and returned. * @param integer $scaleMethod Which method to use for scaling * * @return Image * * @since 1.0 * @throws \LogicException */ public function resize($width, $height, $createNew = true, $scaleMethod = self::SCALE_INSIDE) { // Make sure the resource handle is valid. if (!$this->isLoaded()) { throw new \LogicException('No valid image was loaded.'); } // Sanitize width. $width = $this->sanitizeWidth($width, $height); // Sanitize height. $height = $this->sanitizeHeight($height, $width); // Prepare the dimensions for the resize operation. $dimensions = $this->prepareDimensions($width, $height, $scaleMethod); // Instantiate offset. $offset = new \stdClass(); $offset->x = $offset->y = 0; // Center image if needed and create the new truecolor image handle. if ($scaleMethod == self::SCALE_FIT) { // Get the offsets $offset->x = round(($width - $dimensions->width) / 2); $offset->y = round(($height - $dimensions->height) / 2); $handle = imagecreatetruecolor($width, $height); // Make image transparent, otherwise canvas outside initial image would default to black if (!$this->isTransparent()) { $transparency = imagecolorAllocateAlpha($this->handle, 0, 0, 0, 127); imagecolorTransparent($this->handle, $transparency); } } else { $handle = imagecreatetruecolor($dimensions->width, $dimensions->height); } // Allow transparency for the new image handle. imagealphablending($handle, false); imagesavealpha($handle, true); if ($this->isTransparent()) { // Get the transparent color values for the current image. $rgba = imageColorsForIndex($this->handle, imagecolortransparent($this->handle)); $color = imageColorAllocateAlpha($this->handle, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']); // Set the transparent color values for the new image. imagecolortransparent($handle, $color); imagefill($handle, 0, 0, $color); } // Use resampling for better quality imagecopyresampled($handle, $this->handle, $offset->x, $offset->y, 0, 0, $dimensions->width, $dimensions->height, $this->getWidth(), $this->getHeight()); // If we are resizing to a new image, create a new JImage object. if ($createNew) { // @codeCoverageIgnoreStart $new = new Image($handle); return $new; // @codeCoverageIgnoreEnd } else { // Free the memory from the current handle $this->destroy(); $this->handle = $handle; return $this; } }
public function exifRotate($inputFile, $inputType, $outputFile) { $exif = array(); //Compatible with XF 1.3 as it has method transformByExif $transforms = array(2 => 'flip-h', 3 => 180, 4 => 'flip-v', 5 => 'transpose', 6 => 90, 7 => 'transverse', 8 => 270); if (function_exists('exif_read_data')) { $exif = @exif_read_data($inputFile, 0); } if (isset($exif['Orientation']) && isset($transforms[$exif['Orientation']])) { $transform = $transforms[$exif['Orientation']]; $image = XenForo_Image_Abstract::createFromFile($inputFile, $inputType); if ($image && is_callable(array($image, 'transformByExif'))) { $image->transformByExif($exif['Orientation']); $image->output($inputType, $outputFile, 100); } elseif (is_int($transform)) { //TODO: Refactor code. if (XenForo_Application::getOptions()->imageLibrary['class'] === 'imPecl') { $class = new Imagick($inputFile); foreach ($class->coalesceImages() as $frame) { $frame->rotateImage(new ImagickPixel('none'), $transform); } $class->setimageformat(self::$extensionMap[$inputType]); $class->writeImages($outputFile, true); $class->destroy(); } else { $gd = $this->createImageFromFile($inputFile, $inputType); if ($gd) { $rotate = imagerotate($gd, $transform * -1, imageColorAllocateAlpha($gd, 0, 0, 0, 127)); $this->outputImage($rotate, $inputType, $outputFile); imagedestroy($rotate); imagedestroy($gd); } } } unset($image); } }
function setColor($image, $color, $trans = 0) { $red = 100; $green = 100; $blue = 100; $ret = ''; if (eregi("[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $color, $ret)) { $red = hexdec($ret[1]); $green = hexdec($ret[2]); $blue = hexdec($ret[3]); } // Get a transparent color if trans > 0 if ($trans > 0) { $color_index = @imageColorAllocateAlpha($image, $red, $green, $blue, $trans) or debugMode(__LINE__, $php_errormsg); } else { // Damn, we cannot supress this function... $color_index = imageColorAllocate($image, $red, $green, $blue); } return $color_index; }
/** * Copy an image on another one and converse transparency * * @param resource $destImg * @param resource $srcImg * @param integer $destX * @param integer $destY * @param integer $srcX * @param integer $srcY * @param integer $srcW * @param integer $srcH * @param integer $pct */ public static function imageCopyMergeAlpha(&$destImg, &$srcImg, $destX, $destY, $srcX, $srcY, $srcW, $srcH, $pct = 0) { $destX = (int) $destX; $destY = (int) $destY; $srcX = (int) $srcX; $srcY = (int) $srcY; $srcW = (int) $srcW; $srcH = (int) $srcH; $pct = (int) $pct; $destW = imageSX($destImg); $destH = imageSY($destImg); for ($y = 0; $y < $srcH + $srcY; $y++) { for ($x = 0; $x < $srcW + $srcX; $x++) { if ($x + $destX >= 0 && $x + $destX < $destW && $x + $srcX >= 0 && $x + $srcX < $srcW && $y + $destY >= 0 && $y + $destY < $destH && $y + $srcY >= 0 && $y + $srcY < $srcH) { $destPixel = imageColorsForIndex($destImg, imageColorat($destImg, $x + $destX, $y + $destY)); $srcImgColorat = imageColorat($srcImg, $x + $srcX, $y + $srcY); if ($srcImgColorat > 0) { $srcPixel = imageColorsForIndex($srcImg, $srcImgColorat); $srcAlpha = 1 - $srcPixel['alpha'] / 127; $destAlpha = 1 - $destPixel['alpha'] / 127; $opacity = $srcAlpha * $pct / 100; if ($destAlpha >= $opacity) { $alpha = $destAlpha; } if ($destAlpha < $opacity) { $alpha = $opacity; } if ($alpha > 1) { $alpha = 1; } if ($opacity > 0) { $destRed = round($destPixel['red'] * $destAlpha * (1 - $opacity)); $destGreen = round($destPixel['green'] * $destAlpha * (1 - $opacity)); $destBlue = round($destPixel['blue'] * $destAlpha * (1 - $opacity)); $srcRed = round($srcPixel['red'] * $opacity); $srcGreen = round($srcPixel['green'] * $opacity); $srcBlue = round($srcPixel['blue'] * $opacity); $red = round(($destRed + $srcRed) / ($destAlpha * (1 - $opacity) + $opacity)); $green = round(($destGreen + $srcGreen) / ($destAlpha * (1 - $opacity) + $opacity)); $blue = round(($destBlue + $srcBlue) / ($destAlpha * (1 - $opacity) + $opacity)); if ($red > 255) { $red = 255; } if ($green > 255) { $green = 255; } if ($blue > 255) { $blue = 255; } $alpha = round((1 - $alpha) * 127); $color = imageColorAllocateAlpha($destImg, $red, $green, $blue, $alpha); imageSetPixel($destImg, $x + $destX, $y + $destY, $color); } } } } } }
function rotate($angle) { $new_image = imagerotate($this->image, $angle, imageColorAllocateAlpha($this->image, 250, 250, 250, 0)); imagealphablending($new_image, false); imagesavealpha($new_image, true); $this->image = $new_image; }
/** * Rotate the layer (in degree) * * @param float $degrees */ public function rotate($degrees) { if ($degrees != 0) { if ($degrees < -360 || $degrees > 360) { $degrees = $degrees % 360; } if ($degrees < 0 && $degrees >= -360) { $degrees = 360 + $degrees; } $transparentColor = imageColorAllocateAlpha($this->image, 0, 0, 0, 127); $rotationDegrees = $degrees > 0 ? intval(360 * (1 - $degrees / 360)) : $degrees; // Used to fixed PHP >= 5.5 rotation with base angle 90°, 180° // Rotate the layer background image $imageRotated = imagerotate($this->image, $rotationDegrees, $transparentColor); imagealphablending($imageRotated, true); imagesavealpha($imageRotated, true); unset($this->image); $this->image = $imageRotated; $oldWidth = $this->width; $oldHeight = $this->height; $this->width = imagesx($this->image); $this->height = imagesy($this->image); foreach ($this->layers as $layerId => $layer) { $layerSelfOldCenterPosition = array('x' => $layer->width / 2, 'y' => $layer->height / 2); $smallImageCenter = array('x' => $layerSelfOldCenterPosition['x'] + $this->layerPositions[$layerId]['x'], 'y' => $layerSelfOldCenterPosition['y'] + $this->layerPositions[$layerId]['y']); $this->layers[$layerId]->rotate($degrees); $ro = sqrt(pow($smallImageCenter['x'], 2) + pow($smallImageCenter['y'], 2)); $teta = acos($smallImageCenter['x'] / $ro) * 180 / pi(); $a = $ro * cos(($teta + $degrees) * pi() / 180); $b = $ro * sin(($teta + $degrees) * pi() / 180); if ($degrees > 0 && $degrees <= 90) { $newPositionX = $a - $this->layers[$layerId]->width / 2 + $oldHeight * sin($degrees * pi() / 180); $newPositionY = $b - $this->layers[$layerId]->height / 2; } elseif ($degrees > 90 && $degrees <= 180) { $newPositionX = $a - $this->layers[$layerId]->width / 2 + $this->width; $newPositionY = $b - $this->layers[$layerId]->height / 2 + $oldHeight * -cos($degrees * pi() / 180); } elseif ($degrees > 180 && $degrees <= 270) { $newPositionX = $a - $this->layers[$layerId]->width / 2 + $oldWidth * -cos($degrees * pi() / 180); $newPositionY = $b - $this->layers[$layerId]->height / 2 + $this->height; } else { $newPositionX = $a - $this->layers[$layerId]->width / 2; $newPositionY = $b - $this->layers[$layerId]->height / 2 + $oldWidth * -sin($degrees * pi() / 180); } $this->layerPositions[$layerId] = array('x' => $newPositionX, 'y' => $newPositionY); } } }
public function resize($width, $height, $createNew = true, $scaleMethod = self::SCALE_INSIDE) { if (!$this->isLoaded()) { throw new LogicException('No valid image was loaded.'); } $width = $this->sanitizeWidth($width, $height); $height = $this->sanitizeHeight($height, $width); $dimensions = $this->prepareDimensions($width, $height, $scaleMethod); $offset = new stdClass(); $offset->x = $offset->y = 0; if ($scaleMethod == self::SCALE_FIT) { $offset->x = round(($width - $dimensions->width) / 2); $offset->y = round(($height - $dimensions->height) / 2); $handle = imagecreatetruecolor($width, $height); if (!$this->isTransparent()) { $transparency = imagecolorAllocateAlpha($this->handle, 0, 0, 0, 127); imagecolorTransparent($this->handle, $transparency); } } else { $handle = imagecreatetruecolor($dimensions->width, $dimensions->height); } imagealphablending($handle, false); imagesavealpha($handle, true); if ($this->isTransparent()) { $rgba = imageColorsForIndex($this->handle, imagecolortransparent($this->handle)); $color = imageColorAllocateAlpha($this->handle, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']); imagecolortransparent($handle, $color); imagefill($handle, 0, 0, $color); imagecopyresized($handle, $this->handle, $offset->x, $offset->y, 0, 0, $dimensions->width, $dimensions->height, $this->getWidth(), $this->getHeight()); } else { imagecopyresampled($handle, $this->handle, $offset->x, $offset->y, 0, 0, $dimensions->width, $dimensions->height, $this->getWidth(), $this->getHeight()); } if ($createNew) { $new = new JImage($handle); return $new; } else { $this->destroy(); $this->handle = $handle; return $this; } }
/** * Rotate an image * * @param string source image path to file * @param string destination image path to file * @param integer degrees of the rotation anticlockwise * @param array the array color of the background * @return boolean */ public static function rotate($src_img, $new_img, $degrees = 0, $rgb = array(255, 255, 255)) { list($w, $h, $image_type) = getimagesize($src_img); switch ($image_type) { case 1: $image = imagecreatefromgif($src_img); break; case 2: $image = imagecreatefromjpeg($src_img); break; case 3: $image = imagecreatefrompng($src_img); break; default: $image = false; break; } // rotate if ($degrees) { $image = imagerotate($image, $degrees, imageColorAllocateAlpha($image, $rgb[0], $rgb[1], $rgb[2], 127)); } switch ($image_type) { case 1: imagegif($image, $new_img, 100); break; case 2: imagejpeg($image, $new_img, 100); break; case 3: imagepng($image, $new_img, 0, NULL); break; } @chmod($new_img, 0777); return file_exists($new_img); }