Image compress in Codeigniter3 - php

I have a piece of code where I compress images via Codeigniter gd2 library. However, it turns this photo
into this one
because I set width and height in my code. However, when I remove these 2 lines, $config['quality'] property does not work. How can I solve this problem and save the actual size of the image compressing it?
Here is my code:
$image_datar = $this->upload->data();
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/img/single_courses/'.$image_datar["file_name"];
$config['maintain_ratio'] = false;
$config['quality'] = '60%';
$config['width'] = '750';
$config['height'] = '500';
$config['new_image'] = './assets/img/single_courses/'.$image_datar["file_name"];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$post_image = $image_datar["file_name"];

It's a bit confusing what you are trying to accomplish even after reading the comments, and your code as it specifies the width. If you want it to be 750x500 by have the same ratio (so things don't look "compressed") than you should have $config['maintain_ratio'] = true; which generates:
If you just want to reduce the quality of the image so that the file size is smaller yet keep the same dimensions of the original image than one would think you can comment out the width and height of the config. However, in my testing that yielded the exact same file size as the original image, even when changing the quality down to 10%. Weird, bug? I confirmed this with filesize() and in my os!
Turns out not a bug, but a coded feature:
// If the target width/height match the source, AND if the new file name is not equal to the old file name
// we'll simply make a copy of the original with the new name... assuming dynamic rendering is off.
if ($this->dynamic_output === FALSE && $this->orig_width === $this->width && $this->orig_height === $this->height)
{
if ($this->source_image !== $this->new_image && #copy($this->full_src_path, $this->full_dst_path))
{
chmod($this->full_dst_path, $this->file_permissions);
}
return TRUE;
}
I've tried to figure out a way to get around this but that would require overwriting and messing with the libraries functionality. For now, and if your ok with your image being 1px less in width and height than the original, you can do something like:
$source = $this->frontend_image_upload_path . 'org/upload_original.jpg';
list($width, $height) = getimagesize($source);
$config['image_library'] = 'gd2';
$config['source_image'] = $source;
//$config['maintain_ratio'] = true;
$config['quality'] = '20%';
$config['width'] = $width - 1;
$config['height'] = $height - 1;
$config['new_image'] = $this->frontend_image_upload_path . 'org/new_image.jpg';
$this->load->library('image_lib', $config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}

Related

how to resize image size(quality) with codeigniter image_lib

we are creating an application which allows image upload, now we want to reduce the image size to reduce the page load time, now this is the code i'm using, it doesn't work, image size remains 100% it doesn't reduce, please help maybe i'm missing something or i'm doing something wrong
if(!empty($_FILES['image_field']['name']))
{
$config['upload_path'] = 'image_folder';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '262144';
$config['file_name'] = 'my_image_name';
$this->load->library('upload',$config);
if(!$this->upload->do_upload('image_field'))
{
$this->session->set_flashdata('error','<div class="alert alert-warning">Something went wrong...try again...</div>');
redirect('Controller/function_name');
}
else
{
$type = array('image/png'=>'png','image/jpg'=>'jpg','image/jpeg'=>'jpg');
$config['image_library'] = 'gd2';
$config['source_image'] = base_url().'image_folder'.$config['file_name'].'.'.$type[$_FILES['image_field']['type']];
$config['quality'] = '50%';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
// save to database
}
}
i'm using codeigniter 3.0
You should use without % as integer like that:
$config['quality'] = 50;
$config['image_library'] = 'gd2';
$config['quality'] = 60;
works great adjust the quality and check the image file size it save. will be different.
I also had to set my image_library parameter to "gd" before the quality change started working. I wonder why it didn't work with "gd2"
$config['image_library'] = 'gd';
$config['quality'] = 40;
I found this would not work for me using the GD or GD2 library.
In order for the "quality" to be affected - I needed to use the "ImageMagick" Library.
As stated in the documentation - if you use either the "ImageMagick" or the "NetPBM" library - "you must supply the path": https://codeigniter.com/userguide3/libraries/image_lib.html
On my GoDaddy server the path was "/usr/bin"
$config['source_image'] = $source_image;
$config['library_path'] = '/usr/bin';
$config['image_library'] = 'ImageMagick';
$config['maintain_ratio'] = TRUE;
$config['quality'] = "20%"; // Maintained the aspect ratio and dimensions but reduced the file size by about 60%
$this->image_lib->initialize($config);
if(!$this->image_lib->resize()){
echo "QUCKVIEW Re-sizing - ";
echo $this->image_lib->display_errors();
echo "Image Resize for Grooming Quickview Failed! Contact System Administrator.";
die();
}

Your server does not support the GD function required to process this type of image

Your server does not support the GD function required to process this type of image. is smashing my head. I don't understand which part is wrong! Path should be accurate.
Given that source image is resources/images/upload/BAACN_13853.jpeg
for($i=0; $i<count($result); $i++){
if($result[$i]['condition'] == "Success"){
//**************** RESIZE *******************/
$config['image_library'] = 'GD2';
$config['source_image'] = $result[$i]['msg'];
$config['new_image'] = "/resources/images/upload_thumb/";
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
if($width != NULL || $width != 0){
$config['width'] = $width;
}
if($width != NULL || $width != 0){
$config['height'] = $height;
}
$this->load->library('image_lib', $config);
if($this->image_lib->resize()){
echo $result[$i]['msg']." resized successfully.<br>";
}else{
echo $result[$i]['msg']." resized failed!!<br>";
};
$this->image_lib->clear();
}else{
echo $result[$i]['msg']."<br>";
}
}
To solve this removing the forward slash at the beginning in the following like so:
$config['source_image'] = $result[$i]['msg'];
$config['new_image'] = "/resources/images/upload_thumb/";
Make sure that $result[$i]['msg'] doesn't begin with forward slash
May be you are loading image_lib multiple times. Don't 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);

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"/>

CodeIgniter/PHP/GD2 Image Manipulation is playing up

I have a website going that takes a user's uploaded image, and makes three copies - a 'full' copy to print with (downsized to 1500x1125), a 'web' copy to display online (not coded yet), and finally a thumbnail.
So here's the code - _imageformat() is passed the parameters (which I've confirmed to be correct) from CI's Upload Class:
function _imageformat($fullpath, $shortpath, $width, $height)
{
// We now format the image.
// First, we check if it is landscape or portrait
if ($width >= $height) // It's landscape (or square)
{
// Now create the full printing image
$fullimage = $this->_resize('l', $fullpath, $shortpath, $width, $height);
}
else // It's portrait
{
// Now create the full printing image
$fullimage = $this->_resize('p', $fullpath, $shortpath, $width, $height);
}
}
function _resize($type, $fullpath, $shortpath, $width, $height)
{
// Set up the default Image Manipulation config options
$config['image_library'] = 'gd2';
$config['source_image'] = $fullpath;
$config['maintain_ratio'] = TRUE;
// Shave the '.jpg' from the end to append some nice suffixes we'll use
$newimage = substr($fullpath, 0, -4).'_full'.".jpg";
$config['new_image'] = $newimage;
if ($type == 'l') // If it's landscape
{
$config['width'] = 1500;
$config['height'] = 1125;
}
else if ($type == 'p') // If it's portrait
{
$config['width'] = 1125;
$config['height'] = 1500;
}
// Load the image library with the specified parameters, and resize the image!
$this->load->library('image_lib', $config);
$this->image_lib->resize();
// Create a thumbnail from the full image
$config['source_image'] = $newimage;
$config['new_image'] = substr($fullpath, 0, -9)."_thumb".".jpg";
$config['maintain_ratio'] = TRUE;
$config['width'] = 150;
$config['height'] = 150;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return $newimage;
}
What SHOULD happen: In my uploads folder, there are three images - the original uploaded file (we'll call it image.jpg), the resized file (named image_full.jpg), and the thumbnail (named image_thumb.jpg).
What DOES happen: In my uploads folder, there are only TWO images - the original uploaded file (image.jpg), and the resized file (image_full.jpg). No thumbnail is ever created.
What's interesting, however, ** is that if I place the code for the Thumbnail creation first, it generates the thumbnail image but **NOT the _full (resized) image.
So it appears to me that it won't ever run $this->image_lib->resize() twice. Why not? Is it some amateur mistake I'm making, or have I missed something obvious?! :P
Thanks!
Jack
Edit: I should point out that yes, I know I'm loading the image_lib library twice. I fathomed this was the only way of passing new parameters to it. I also tried, after resizing the full image, calling $this->_thumbnail() which loaded the library again there. But still the same issue occurred.
Edit 2: I've also tried using $this->image_lib->clear() - still no luck.
You should load the library only once and initialize it with different configs:
$this->load->library('image_lib');
// full image stuff
$this->image_lib->initialize($config);
$this->image_lib->resize();
// thumbnail stuff
$this->image_lib->initialize($config);
$this->image_lib->resize();

Categories