Codeigniter Image Manipulation Class : Resize and Crop on multiple files - php

I'm struggling to get the CodeIgniter Image Manipulation working correctly. Either it's a bug or I'm just not seeing it. I hope someone can help me with it. Thanks in advance!
On the script: I want to create thumbnails (176w x 132h). The input images are in different sizes and ratios. In order to always get this size I first resize them to fit the max width or height (depending on image orientation) and then crop in the center.
I've tried to do it all in 1 method. That didn't work, so I created two seperate methods.
resize_img()
and
crop_img().
When I run resize_img() on 3 different files, it works. If after that I use crop_img() on these thumbnails the 1th method created, it works. If I combine the two, or use them after one another, it doesn't.
I've tried $this->image_lib->clear();, unsetting the config files. I even created two config files, just to be sure.
I'm getting different all kind of errors from GD2, but the problem is, that after resize_img() creates the thumbnail, the crop_img() won't crop it. After that it all goes south, and the next images can't be opened. Write premissions are checked, both on folder and files.
Unable to save the image. Please make sure the image and file
directory are writable. The path to the image is not correct. Your
server does not support the GD function required to process this type
of image.
Full code:
<?PHP
class Imagetest extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->library('image_lib');
}
function index()
{
$testimg1 = 'uploads/test/1.png';
$testimg2 = 'uploads/test/2.png';
$testimg3 = 'uploads/test/3.png';
$this->resize_img($testimg1);
$this->crop_img($testimg1);
$this->resize_img($testimg2);
$this->crop_img($testimg2);
$this->resize_img($testimg3);
$this->crop_img($testimg3);
}
function image_thumb_name($img = null)
{
if(!empty($img)) {
$exploded = explode('.', $img);
return $exploded['0'] . '_thumb.' . $exploded['1'];
}
}
function get_axis($img)
{
// Default values
$output['x_axis'] = 0;
$output['y_axis'] = 0;
// Settings
$config['height'] = 132;
$config['width'] = 176;
if ($img_dim = getimagesize($img)) {
list($thumb_width, $thumb_height) = $img_dim;
} else {
echo '<h1> ERROR HERE TOO</h1>';
return false;
}
if ($thumb_width > $config['width']) {
$output['x_axis'] = (($thumb_width - $config['width']) / 2) ;
} else if ($thumb_height > $config['height']) {
$output['y_axis'] = (($thumb_height - $config['height']) / 2);
}
return $output;
}
function resize_img($img)
{
$config = array();
echo 'Processing: '. $img .'<br/>'; // Debug
if ($img_dim = getimagesize($img)) {
list($image_width, $image_height) = $img_dim;
} else {
echo '<h1> ERROR HERE </h1>';
}
// create a thumbnail
$config['image_library'] = 'GD2';
$config['source_image'] = $img;
$config['quality'] = 100;
$config['height'] = 132;
$config['width'] = 176;
$config['create_thumb'] = TRUE;
$config['maintain_ratio']= TRUE;
$config['master_dim'] = ($image_width > $image_height) ? 'height' : 'width';
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
echo '<img src="../'.$this->image_thumb_name($img).'" /> <br/>'; // Debug
$this->image_lib->clear();
unset($config);
}
function crop_img($img)
{
$config2 = array();
// Crop that thumbnail
$config2['image_library'] = 'GD2';
$config2['quality'] = 100;
$config2['height'] = 132;
$config2['width'] = 176;
$config2['source_image'] = $this->image_thumb_name($img);
$axis = $this->get_axis($config2['source_image']);
$config2['x_axis'] = $axis['x_axis'];
$config2['y_axis'] = $axis['y_axis'];
$config2['maintain_ratio'] = FALSE;
$config2['create_thumb'] = FALSE;
$this->image_lib->initialize($config2);
if (!$this->image_lib->crop()) {
echo $this->image_lib->display_errors();
}
echo '<img src="../'.$config2['source_image'].'" /> <br/>'; // Debug
$this->image_lib->clear();
unset($config2);
}
}

Got it!
I've set the create_thumb option to FALSE, and used the new_image parameter in the resize_img method. The effect is the same, but the built-in create_tumb function is not being used.
It's a bug IMHO, but it's working now :)
$config['create_thumb'] = FALSE;
$config['new_image'] = $this->image_thumb_name($img);

The problem is with your $config['source_image']
var_dump($config['source_image']);
see what you get.
If the file is in images folder in root folder, the $config['source_image] = 'images/'.$img.
Also make sure all the exploding functions returning the correct file name. (return and echo to check).
1st, eliminate file not found error. After that, see what error comes.

You can use Kodem's Image Resize Service. You can resize, crop any image with just a http call. Can be used casually in the browser or used in your production app.

Related

Images get rotated by 90 Whole resizing using gd2 in CodeIgniter

I had used gd2 library to resize image.But some images got rotated by 90 degree after resized but not all image.I hadn't used any rotation.What may be the reason behind this?Do I need to set anything other configuration?
My code is here :
if(isset($_FILES) && !empty($_FILES)){
$item_images = $_FILES;
$this->load->library('upload');
$this->load->library('image_lib');
$config['upload_path'] = './temp/';
$config['allowed_types'] = '*';
$this->upload->initialize($config);
//print_r($item_images);
foreach($item_images as $ind=>$img_name){
if($this->upload->do_upload($ind)){
$data_image = $this->upload->data();
//for cropping
$config_crop['image_library'] = 'gd2';
$config_crop['source_image'] = $config['upload_path'] . $data_image['file_name'];
$config_crop['create_thumb'] = FALSE;
$config_crop['maintain_ratio'] = TRUE;
$config_crop['width'] = 300;
$config_crop['height'] = 300;
//$config_crop['rotation_angle'] = '0';
//$config_crop['x_axis'] = '100';
//$config_crop['y_axis'] = '40';
$this->image_lib->initialize($config_crop);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
$image_thumb = $this->s3_model->upload_image('thumb_'.$img_name['name'] ,$config['upload_path'] . $data_image['file_name']);
if($image_thumb){
$result = $this->s3_model->upload_image($img_name['name'] ,$img_name['tmp_name']);
//unlink($config['upload_path'] . $data_image['file_name']);
}
if(! $result){
$flag = false; //Error in uploading image.
break;
}
}
}
Do you have a OSx working machine?
In my case, a pic, that in my Mac was shown correctly, indeed was turned sideways, that is because OSX preview detects CellPhone orientation while the pic was taken....
The server not, neither windows machines... so that was driving me crazy...
Being or not this your case, you can use exif_read_data() function. This will give you orientation data if it exists on photo's metadata.
Check here: How to detect shot angle of photo, and auto rotate for website display like desktop apps do on viewing?

image cropping with codeigniter no GD library - GD2 is intalled

I am working on media library for a website at the moment, and one of the features is that user can create a cropped version of an image that they upload.
My problem however is this, when I try and crop the image, I get the following error,
The path to the image is not correct.
Here is my code,
$config['image_library'] = 'gd2';
$config['source_image'] = "/media/images/products/".$this->data['image'];
//die($config['source_image']);
$config['maintain_ratio'] = FALSE;
$config['x_axis'] = $this->input->post('x');
$config['y_axis'] = $this->input->post('y');
$config['width'] = $this->input->post('w');
$config['height'] = $this->input->post('h');
$config['dynamic_output'] = FALSE;
$config['create_thumb'] = TRUE;
$this->load->library('image_lib', $config);
if(!$this->image_lib->crop()) {
if($this->input->post('isAjax') == "1") {
echo json_encode($this->image_lib->display_errors());
} else {
$this->data['image_error'] = $this->image_lib->display_errors();
$this->template->build('/admin/media/crop', $this->data);
}
} else {
$filename = base_url()."media/images/products/".$this->data['image'];
$extension_pos = strrpos($filename, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($filename, 0, $extension_pos) . '_thumb' . substr($filename, $extension_pos);
if($this->input->post('isAjax') == 1) {
echo json_encode($success = array('message' => 'Image Cropped'));
} else {
$this->data['success'] = "Image Cropped";
$this->template->build('/admin/media/crop', $this->data);
}
}
So I though I would change $config['source_image'] to the following,
$config['source_image'] = "./media/images/products/".$this->data['image'];
however that just leaves with this message,
Your server does not support the GD function required to process this type of image.
Am I doing something fundamentally wrong? I am only trying to crop a simple .png, and the file certainly exists on my server, and I most definatly have GD2 installed.
The is most likely just a file path issue (CI is pretty good about accurate, relevant error messages). Here are the steps I would take to resolve it:
var_dump(file_exists($config['source_image']) to see if PHP finds the file. I'd be shocked by a "true" response here.
If the filesystem is case-sensitive, make sure that's not the problem
Check the include path (I assume regular includes are working fine if CI gets this far...)
More of an anti-step, but DON'T use $_SERVER['DOCUMENT_ROOT'], as a commenter suggests. FC_PATH (or other CI-defined constants) should get you the base path you need.
Happy hunting.

Trying to resize an image twice in a function and it's only resizing it once

I'm trying to have a user upload a file and then my function will resize that photo to something like 800x600 and then resize that file to 165x165. With my code, it's only resizing it to 165x165, but if I comment that section out, it resizes it to 800x600.
What can I do to get it to resize both?
/**
* addPhoto - function which shows the add photo page
*/
function addPhoto($album)
{
$album = rawurldecode($album);
ini_set('upload_max_filesize', '4M');
ini_set('post_max_size', '12M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
$config['upload_path'] = './assets/images/photoAlbums/'.$album.'/';
$config['allowed_types'] = 'jpg|jpeg|pjpeg';
$config['max_size'] = '4096'; // that's 4MBs
$config['max_width'] = '4000';
$config['max_height'] = '3000';
$config['remove_space'] = TRUE;
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userFile')) { // if there are errors uploading the file...
$content_data['error'] = array('error' => $this->upload->display_errors());
} else { // else there are NO errors, we need to resize it, and ditch that huge ass original
$image = $this->upload->data();
$uploadedFile = $image['file_name'];
$this->load->library('image_lib');
$thumbConfig['image_library'] = 'gd2';
$thumbConfig['source_image'] = $image['full_path'];
$thumbConfig['create_thumb'] = FALSE;
$thumbConfig['maintain_ratio'] = TRUE;
$thumbConfig['width'] = 800;
$thumbConfig['height'] = 600;
$this->image_lib->initialize($thumbConfig);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
$thumbConfig['image_library'] = 'gd2';
$thumbConfig['source_image'] = $image['full_path'];
$thumbConfig['create_thumb'] = TRUE;
$thumbConfig['maintain_ratio'] = FALSE;
$thumbConfig['width'] = 165;
$thumbConfig['height'] = 165;
$this->image_lib->initialize($thumbConfig);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$content_data['firstName'] = $this->session->userdata('firstName');
$data['sess'] = $this->session;
$data['content'] = $this->load->view('member/addPhoto_success', $content_data, true);
$this->load->view('template/admin', $data);
}
}
for the second time running the image_lib, you're going to want to avoid overwriting the file by specifying the new file for it to create:
after:
$thumbConfig['height'] = 165;
add:
$thumbConfig['new_image'] = $image['file_path'] . "thumb_" . $image['file_name'];
so if your resized 800 x 600 image resides at /my/upload/path/foo.jpg,
this will create a thumb at /my/upload/path/thumb_foo.jpg.
If you want to create two new resized images and leave the original intact, you need to add
$config['create_thumb'] = TRUE;
or
$config['new_image'] = '/path/to/new_image.jpg';
to the first section.
According to your code, you will overwrite the original file with an 800x600 version and then create a 165x165 thumbnail.
I think you are missing this line on the first resize:
$thumbConfig['source_image'] = $image['full_path'];
I know this is a very old question, but I just ran into the same issue.
$config['create_thumb'] = true
did not create a new file.
Adding the thumb marker configuration:
$config['thumb_marker'] = '_thumb'
worked.
It seems that _thumb is not the default for thumb_marker.

CodeIgniter image crop only on dynamic output

I'm trying to crop an image in CodeIgniter, using the built in image manipulation class. The code below works fine, you get a resized image output to the browser. However, when you remove the "$config['dynamic_output'] = TRUE;" line it no longer crops the image, and just saves the original image instead. What am I doing wrong?!
Any help is much appreciated, thanks!
public function crop() {
$config['library_path'] = '/usr/local/bin';
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/static/images/moose_resized.jpg';
$config['new_image'] = $_SERVER['DOCUMENT_ROOT'].'/static/images/moose_thumb.jpg';
$config['x_axis'] = '0';
$config['y_axis'] = '74';
$config['width'] = '222';
$config['height'] = '111';
$config['maintain_ratio'] = FALSE;
$config['quality'] = '100';
$config['dynamic_output'] = TRUE;
$this->load->library('image_lib', $config);
$this->image_lib->crop();
if ( ! $this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
$this->load->view('crop');
}
OK, so nobody get any points because they didn't spot the stupid mistake in the code above!
$this->image_lib->crop();
if ( ! $this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
In a moment of temporary insanity I added in the crop line, rather than replacing the resize one in the if statement. Duh!

Resizing an image on the fly using CodeIgniter

I am working on a script that downloads a file from Dropbox, supposed to resize that image and then shoot it up to an S3 bucket.
For some reason, I can't get the image to resize.
I keep getting the following error:
The path to the image is not correct.
Your server does not support the GD function required to process this type of image.
Code Base:
public function resize_test() {
$postcard_assets = $this->conn->getPostcardDirContent("folder_name", "Photos", TRUE);
foreach($postcard_assets['contents'] as $asset) {
$file = pathinfo($asset['path']);
$original_file = $this->conn->downloadFile($asset['path']);
$raw_file = sha1($file['basename']);
$s3_file_name = "1_{$raw_file}.{$file['extension']}";
$this->resize_photo($original_file);
$this->s3->putObject($s3_file_name, $original_file, 's3-bucket-name', 'public-read');
$s3_check = $this->s3->getObjectInfo($s3_file_name, 's3-bucket-name');
if($s3_check['content-length'] > 0) {
krumo($s3_check);
exit();
}
}
}
private function resize_photo($photo) {
$config['image_library'] = 'imagemagick';
$config['source_image'] = $photo;
$config['maintain_ratio'] = TRUE;
$config['width'] = 640;
$config['height'] = 480;
$this->load->library('image_lib', $config);
if(!$this->image_lib->resize()) {
exit($this->image_lib->display_errors());
}
}
Dropbox API DownloadFile:
public function downloadFile($file) {
$this->setTokens();
return $this->conn->getFile($file);
}
Anyone know what I might be doing wrong?
Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);
to
$this->image_lib->initialize($config);
I'm doing image resizing with CI using ImageMagick just like you are. You need the following to get this to work:
imagemagick should be installed. You can test it from the command line using the 'convert' command
imagick needs to be installed, this is the PHP library that binds to imagemagick
ImageMagick itself depends on various other libraries such as libjpeg and libpng. Make sure those are installed as well
Simpy do a phpinfo() and scroll down to 'imagick'. Check whether it is there and then check the 'supported file formats' heading to see if the file type you are wanting to resize is there.
If all of the above are correct and it still does not work, you should not forget to include the path to imagemagick in your code:
$config['library_path'] = '/usr/local/bin';
I went through all this pain before so I hope this helps you :)
For Multiple resize below code worked for me.
$config['create_thumb'] = FALSE; //to avoid _thumb prefixing
$config['maintain_ratio'] = TRUE;
$config['width'] = 250;
$config['height'] = 250;
$config['new_image'] = 'thumb_250x250_'.$file_name; // new name
$CI->load->library('image_lib', $config, 'abc'); //abc to avoid instance caching.
$CI->abc->resize();
unset($CI->abc); //unsetting instance.
$config['width'] = 100;
$config['height'] = 100;
$config['new_image'] = 'thumb_100x100_'.$file_name; // new name
$CI->load->library('image_lib', $config, 'xyz'); // xyz to avoid instance caching.
$CI->xyz->resize();
unset($CI->xyz); // unsetting instance.
You need to use $config['new_image'] = '/path/to/new_image.jpg'; in your resize_photo function.
Read http://codeigniter.com/user_guide/libraries/image_lib.html
Actually you are trying to load the image library twice. Since you also initialize the config array on the very same line, the array never gets loaded into the library.
Change your code to this:
//this
$this->load->library('image_lib', $config);
//to this
$this->load->library('image_lib');
$this->image_lib->initialize($config);
and it will work perfectly.
See if you can actually open the original saved image before you try to resize it. I was decoding a base64 uploaded image while using a preg_replace. For some reason, which I still can't track down... it was removing like so
$file = preg_replace('/data.*base64,/', '', chunk_split($this->post('myimg'));
it would return this: [removed]/9....etc. which when base64 decoded... obviously isnt a valid image file.. so the resize wouldnt work. I had to add a
$file = substr($file,9);
to then remove the [removed]. extra work and took me while to figure out, but now I can resize images.
Side Question... Why is preg_replace adding [removed]??? Sigh... php.
//Make controller named "image.php"
class Image extends CI_Controller {
public function index($width, $height, $image_path)
{
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/'.$image_path;
$config['dynamic_output'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
echo $this->image_lib->resize();
}
}
?>
//Call from view page
<img src="<?php echo ("index.php/image/index/150/150/".$luserdata[0]'profile_image']);?>" alt="resized mage1"/>

Categories