Laravel 5 imagepng not working - php

I'm trying to create a script that takes a certain part of an image but when i use imagepng, it returns me this:
Here's my code
$name = $path;
header("Content-type: image/png");
if (strpos($name, '..') !== false) {
exit(); // name in path with '..' in it would allow for directory
traversal.
}
$size = $face_size > 0 ? $face_size : 100;
//Grab the skin
$src = imagecreatefrompng("./skins/" . $name . ".png");
//If no path was given or no image can be found, then create from default
if (!$src) {
$src = imagecreatefrompng("./skins/default.png");
}
//Start creating the image
list($w, $h) = getimagesize("./skins/" . $name . ".png");
$w = $w / 8;
$dest = imagecreatetruecolor($w, $w);
imagecopy($dest, $src, 0, 0, $w, $w, $w, $w); // copy the face
// Check to see if the helm is not all same color
$bg_color = imagecolorat($src, 0, 0);
$no_helm = true;
// Check if there's any helm
for ($i = 1; $i <= $w; $i++) {
for ($j = 1; $j <= 4; $j++) {
// scanning helm area
if (imagecolorat($src, 40 + $i, 7 + $j) != $bg_color) {
$no_helm = false;
}
}
if (!$no_helm)
break;
}
// copy the helm
if (!$no_helm) {
imagecopy($dest, $src, 0, -1, 40, 7, $w, 4);
}
//prepare to finish the image
$final = imagecreatetruecolor($size, $size);
imagecopyresized($final, $dest, 0, 0, 0, 0, $size, $size, $w, $w);
//if its not, just show image on screen
imagepng($final);
//Finally some cleanup
imagedestroy($dest);
imagedestroy($final);
I used this code previously without any framework and it worked just fine, I don't know where it comes from.

Laravel and other frameworks use Middlewares, so when your controller method is done the application isn't ready to send the response yet. You can solve the problem by storing the output of the imagepng function in an internal buffer and send it properly(I think there isn't another solution if you want to use GD), also you have to use Laravel's function to set the HTTP headers instead of the header function.
Here is a simple example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AppController extends Controller
{
//Generates an image with GD and sends it to the client.
public function image(){
$im = imagecreatetruecolor(800, 420);
$orange = imagecolorallocate($im, 220, 210, 60);
imagestring($im, 3, 10, 9, 'Example image', $orange);
//Turn on output buffering
ob_start();
imagepng($im);
//Store the contents of the output buffer
$buffer = ob_get_contents();
// Clean the output buffer and turn off output buffering
ob_end_clean();
imagedestroy($im);
return response($buffer, 200)->header('Content-type', 'image/png');
}
}
You can look at this, I hope it will help you.
Although it works, it isn't the best method, I recommend you to use Imagick(if you can) instead of GD.

Related

Change image in PDF

Hi I keep getting this error:
Runtime Deprecated code usage - Imagick::clone method is deprecated and it's use should be avoided
It is always around this function:
protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
if (empty($filehash)) {
$filehash = md5($file);
}
// create temp image file (without alpha channel)
$tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
// create temp alpha file
$tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
if (extension_loaded('imagick')) { // ImageMagick
// ImageMagick library
$img = new Imagick();
$img->readImage($file);
// clone image object
$imga = $img->clone();
// extract alpha channel
$img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
$img->negateImage(true);
$img->setImageFormat('png');
$img->writeImage($tempfile_alpha);
// remove alpha channel
$imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
$imga->setImageFormat('png');
$imga->writeImage($tempfile_plain);
} else { // GD library
// generate images
$img = imagecreatefrompng($file);
$imgalpha = imagecreate($wpx, $hpx);
// generate gray scale palette (0 -> 255)
for ($c = 0; $c < 256; ++$c) {
ImageColorAllocate($imgalpha, $c, $c, $c);
}
// extract alpha channel
for ($xpx = 0; $xpx < $wpx; ++$xpx) {
for ($ypx = 0; $ypx < $hpx; ++$ypx) {
$color = imagecolorat($img, $xpx, $ypx);
$alpha = ($color >> 24); // shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)
$alpha = (((127 - $alpha) / 127) * 255); // GD alpha is only 7 bit (0 -> 127)
$alpha = $this->getGDgamma($alpha); // correct gamma
imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
}
}
imagepng($imgalpha, $tempfile_alpha);
imagedestroy($imgalpha);
// extract image without alpha channel
$imgplain = imagecreatetruecolor($wpx, $hpx);
imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
imagepng($imgplain, $tempfile_plain);
imagedestroy($imgplain);
}
// embed mask image
$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
// embed image, masked with previously embedded mask
$this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
// remove temp files
unlink($tempfile_alpha);
unlink($tempfile_plain);
}
All I was trying to do is change the image inside the PDF, but for some reason it won't allow me. I tried looking online but I could not find the same issue. Can anyone help please?
As explained in the Imagick::clone documentation, this method is indeed deprecated, and to be replace by an object cloning.
Replace the line $imga = $img->clone(); by $imga = clone $img;

How to store and get image from a image variable (SESSION)?

here is my code, test1.php works, test2.php not works.
test1.php:
<?php
session_start();
header('Content-type: image/jpeg');
$text = rand(1000,9999);
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
$_SESSION['image'] = $image;
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
test2.php:
<?php
session_start();
header('Content-type: image/jpeg');
$image_session = $_SESSION['image'];
imagejpeg($image_session);
?>
As you can see, test1.php create a random image.
I can use:
<img src="test1.php">
to show the image from test1.php in any pages.
but, I want to use if else statement in other php files.
for example:
if users click submit button and enter nothing(no answer), the image will still the same, they have to answer the same question. if failed, the image will change.
I don't want to use javascript to prevent users input nothing and store images in disk.
so, I think that I need a variable to store the image that can be used again.
but I found I cannot use above method.
how can I achieve this?
imagecreate() returns a resource representing given image. PHP's sessions cannot store resource-type variables (more precisely - PHP is unable to serialize them upon script end), see http://php.net/manual/en/function.session-register.php:
Note: It is currently impossible to register resource variables in a
session. ...
You may serialize the image to a string and store this string to the session (not tested):
test1.php:
...
ob_start();
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();
$_SESSION['image'] = $contents;
test2.php:
header('Content-type: image/jpeg');
die($_SESSION['image']);
Without knowing much about the context, can't you do something like
session_start();
$_SESSION['randomValue'] = mt_rand(1000,9999);
if(someValueIsEntered){
$_SESSION['randomValue'] = mt_rand(1000,9999);
}
echo "<img src='test.php?random=".$_SESSION['randomValue']."'/>";
Test.php
$randomValue = filter_input(INPUT_GET, 'random');
header('Content-type: image/jpeg');
$text = $randomValue;
$font_size = 5;
$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $font_size, 0, 0, $text, $text_color);
imagejpeg($image);
Multiple parameters example:
Store the information about the image in an array.
session_start();
if(!isset($_SESSION['imageData']){
$_SESSION['imageData'] = array(
"random" => mt_rand(1000,9999),
"x1" => mt_rand(0,10),
"x2" => mt_rand(0,10)
);
}
if(someValueIsEntered){
//Randomize array again.
}
$imageString = "test.php";
foreach ($_SESSION['imageData'] as $key => $value) {
$index = current($array);
if($index == 0) {
$seperator = "?";
} else {
$seperator = "&";
}
$imageString .= $seperator.$key."=".$value;
}
echo "<img src='".$imageString."'/>";
And just call them in the test.php then.

Rotate and crop image batch

EDIT: please forget about this question! I made a stupid error in the original code.
The example code works as expected!
I'm trying to rotate AND crop images.
I have this so far:
$w = 100;
$h = 400;
$img1 = imagecreatefromjpeg('image1.jpg');
$img2 = imagecreatefromjpeg('image2.jpg');
for ($i = 0; $i < 2; $i++) {
${'img'.$i + 3} = imagecreatetruecolor($h, $h);
imagecopy(${'img'.$i + 3}, ${'img'.$i + 1}, 0, 0, 0, 0, $w, $h);
${'img'.$i + 3} = imagerotate(${'img'.$i + 3}, 90, 0);
${'img'.$i + 3} = imagecrop(${'img'.$i + 3}, array(0, 0, $h, $w));
imagejpeg(${'img'.$i + 3});
imagedestroy(${'img'.$i + 3});
imagedestroy(${'img'.$i + 1});
}
So what I essentially do is open some JPGs, create new images, copy the JPGs into the new images and then crop the images.
Alas this results in empty images ...
What am I doing wrong?
No idea if this will make any difference to the lack of output - but what do $img1 & $img2 do - they don't get used as far as i can see?
#error_reporting( E_ALL );
$w = 100;
$h = 400;
$img1 = imagecreatefromjpeg('image1.jpg');
$img2 = imagecreatefromjpeg('image2.jpg');
for ($i = 0; $i < 3; $i++) {
$new=${'img'.$i + 3};
$src=${'img'.$i + 1};
$new = imagecreatetruecolor($h, $h);
imagecopy( $new, $src, 0, 0, 0, 0, $w, $h);
$new = imagerotate($new, 90, 0);
$new = imagecrop($new, array(0, 0, $h, $w));
imagejpeg($new);
imagedestroy($new);
imagedestroy($src);
break;/* just to see if it gets this far*/
}
Firstly, you should consider using image copy resampled for a better quality of result from the process.
Then, you need to correctly use the imagejpeg function, currently you are simply loading the JPGs and outputting them directly, which may be what you want but you're in a loop and you can't loop load multiple images directly to the same file. It also means that the image you're seeing (or not) is the final image in the set.
Your Problem is that your for loop runs THREE times but your only have data associated with the first two instances, but the third instance is empty, and as this is the most recent this is the only instance output to the browser.
So:
1) Save the images you have generated with imagejpeg($data,$filename);. You can define a filename as $filename = $img+3.".jpg"; or similar.
2) It would also be much easier to debug and read your code if you used arrays instead of numerically incremented variables, that's a very messy way of writing code!
3) If you do want to output the image directly to the browser you need PHP to supply a header such as header('Content-Type: image/jpeg'); before outputting the contents of imagejpeg.
A Rehash of your code:
$w = 100;
$h = 400;
$img[1] = imagecreatefromjpeg('image1.jpg');
$img[2] = imagecreatefromjpeg('image2.jpg');
for ($i = 3; $i < 5; $i++) {
$img[$i] = imagecreatetruecolor($h, $h);
$j = $i -2;
imagecopyresampled($img[$i], $img[$j], 0, 0, 0, 0, $h, $h, $w, $h,);
// this function also contains destination width and destination
// height, which are equal to the size of the destination image so
// are set as $h, $h in the function above.
$img[$i] = imagerotate($img[$i], 90, 0);
$img[$i] = imagecrop($img[$i], array(0, 0, $h, $w));
$filename = "image-".$i.".jpg";
imagejpeg($img[$i], $filename);
imagedestroy($img[$i]);
imagedestroy($img[$j]);
}

PHP session problem-- captcha/Joomla

I have a Joomla component which calls a helper function to create a captcha image. Everything works fine when sh404 is disabled, but when sh404 is enabled the session variable for the security image isn't being set correctly so when you submit the form you get 'Invalid Captcha' message. The funny thing is if you submit another 5-6 times, it validates fine and submits. I've tried just about everything I can think of - when I echo the session variable and submitted captcha code it appears that the session is a step behind - for example:
If I submit the form the first time and echo the session variable and submitted code, it looks like the session variable is not being set in time - I get a blank value for the session variable. Then I submit the form again and the session variable is the value of the previous captcha image. Here's the code that generates and validates the captcha. Thanks!
//Generate Captcha image link
function Captchalink($capid = ''){
return 'index.php?option=com_mycomponent&view=home&task=newCaptcha&capid='.$capid;
}
function generateCode($characters) {
/* list all possible characters, similar looking characters and vowels have been removed */
$possible = '23456789bcdfghjkmnpqrstvwxyz';
$code = '';
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
return $code;
}
function CaptchaSecurityImages($capid = '') {
$font = dirname(__FILE__).DS."monofont.ttf";
$width = 90;
$height = 30;
$characters = 6;
$session =& JFactory::getSession();
//Clean buffers
while (ob_get_level()) {
ob_end_clean();
}
// start output buffering
if (ob_get_length() === false) {
ob_start();
}
$code = mycomponentHTML::generateCode($characters);
/* font size will be 75% of the image height */
$font_size = $height * 0.75;
$image = #imagecreate($width, $height) or die('Cannot initialize new GD image stream');
/* set the colors */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$noise_color = imagecolorallocate($image, 100, 120, 180);
/* generate random dots in background */
for( $i=0; $i<($width*$height)/3; $i++ ) {
imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
}
/* generate random lines in background */
for( $i=0; $i<($width*$height)/150; $i++ ) {
imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
}
/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function');
$x = ($width - $textbox[4])/2;
$y = ($height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code) or die('Error in imagettftext function');
/* output captcha image to browser */
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
/* set session variable for newly created code */
$session->set('security_code_'.$capid, md5($code));
ob_end_flush();
die();
}
function CaptchaValidate($capid = ''){
$session =& JFactory::getSession();
if( $session->get('security_code_'.$capid) == md5(JRequest::getVar('security_code_'.$capid)) ) {
$session->clear('security_code_'.$capid);
return true;
}else{
return false;
}
}

Wrong colors when merging images with PHP

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

Categories