I have got a custom model for my images that should be able to locate the correct folder. And then let me resize images by doing this in model. example $this->model_tool_image->resize($this->settings->get('config_image'), 100, 100);
I know codeigniter has one but not what I am after.
For some reason not picking up images even though they are there. I think it may be a problem with the directories? All images are kept in base_url() . 'images/catalog' The posted image name can be got from DB fine.
Error: Could not load image ! Very strange I have defined path on model and it is working.
No images display
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_tool_image extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->library('images');
define('DIR_IMAGE', base_url('image/catalog') .'/');
}
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename)) {
return;
}
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$old_image = $filename;
$new_image = DIR_IMAGE . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
if (!is_file(DIR_IMAGE . $new_image) || (filectime(DIR_IMAGE . $old_image) > filectime(DIR_IMAGE . $new_image))) {
$path = '';
$directories = explode('/', dirname(str_replace('../', '', $new_image)));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_IMAGE . $path)) {
#mkdir(DIR_IMAGE . $path, 0777);
}
}
list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $old_image);
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $new_image);
} else {
copy(DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
}
}
if ($this->input->server('HTTPS')) {
return HTTPS_SERVER . 'image/catalog/' . $new_image;
} else {
return HTTP_SERVER . 'image/catalog/' . $new_image;
}
}
}
Controller
$this->load->library('settings'); // Gets image from db OK example; nemo.png
$this->load->model('admin/tool/model_tool_image');
echo DIR_IMAGE;
if (!empty($this->input->post('config_image')) ) {
$data['config_image'] = $this->input->post('config_image');
} else {
$data['config_image'] = $this->settings->get('config_image');
}
if (!empty($this->input->post('config_image')) && is_file(DIR_IMAGE . $this->input->post('config_image'))) {
$data['thumb'] = $this->model_tool_image->resize($this->input->post('config_image'), 100, 100);
} elseif ($this->settings->get('config_image') && is_file(DIR_IMAGE . $this->settings->get('config_image'))) {
$data['thumb'] = $this->model_tool_image->resize($this->settings->get('config_image'), 100, 100);
} else {
$data['thumb'] = $this->model_tool_image->resize(base_url() . 'image/no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize(base_url() . 'image/no_image.png', 100, 100);
return $this->load->view('setting/settings', $data);
Custom Images Library
<?php
class Images {
private $file;
private $image;
private $info;
public function __construct($file = '') {
if (file_exists($file)) {
$this->file = $file;
$info = getimagesize($file);
$this->info = array(
'width' => $info[0],
'height' => $info[1],
'bits' => isset($info['bits']) ? $info['bits'] : '',
'mime' => isset($info['mime']) ? $info['mime'] : ''
);
$this->image = $this->create($file);
} else {
exit('Error: Could not load image ' . $file . '!');
}
}
private function create($image) {
$mime = $this->info['mime'];
if ($mime == 'image/gif') {
return imagecreatefromgif ($image);
} elseif ($mime == 'image/png') {
return imagecreatefrompng($image);
} elseif ($mime == 'image/jpeg') {
return imagecreatefromjpeg($image);
}
}
public function save($file, $quality = 90) {
$info = pathinfo($file);
$extension = strtolower($info['extension']);
if (is_resource($this->image)) {
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($this->image, $file, $quality);
} elseif ($extension == 'png') {
imagepng($this->image, $file);
} elseif ($extension == 'gif') {
imagegif ($this->image, $file);
}
imagedestroy($this->image);
}
}
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->info['width'] || !$this->info['height']) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->info['width'];
$scale_h = $height / $this->info['height'];
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png') {
return;
}
$new_width = (int)($this->info['width'] * $scale);
$new_height = (int)($this->info['height'] * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $width;
$this->info['height'] = $height;
}
public function watermark($file, $position = 'bottomright') {
$watermark = $this->create($file);
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
switch($position) {
case 'topleft':
$watermark_pos_x = 0;
$watermark_pos_y = 0;
break;
case 'topright':
$watermark_pos_x = $this->info['width'] - $watermark_width;
$watermark_pos_y = 0;
break;
case 'bottomleft':
$watermark_pos_x = 0;
$watermark_pos_y = $this->info['height'] - $watermark_height;
break;
case 'bottomright':
$watermark_pos_x = $this->info['width'] - $watermark_width;
$watermark_pos_y = $this->info['height'] - $watermark_height;
break;
}
imagecopy($this->image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0, 120, 40);
imagedestroy($watermark);
}
public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
$image_old = $this->image;
$this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y);
imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y, $this->info['width'], $this->info['height']);
imagedestroy($image_old);
$this->info['width'] = $bottom_x - $top_x;
$this->info['height'] = $bottom_y - $top_y;
}
public function rotate($degree, $color = 'FFFFFF') {
$rgb = $this->html2rgb($color);
$this->image = imagerotate($this->image, $degree, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
$this->info['width'] = imagesx($this->image);
$this->info['height'] = imagesy($this->image);
}
private function filter($filter) {
imagefilter($this->image, $filter);
}
private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') {
$rgb = $this->html2rgb($color);
imagestring($this->image, $size, $x, $y, $text, imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
}
private function merge($file, $x = 0, $y = 0, $opacity = 100) {
$merge = $this->create($file);
$merge_width = imagesx($merge);
$merge_height = imagesy($merge);
imagecopymerge($this->image, $merge, $x, $y, 0, 0, $merge_width, $merge_height, $opacity);
}
private function html2rgb($color) {
if ($color[0] == '#') {
$color = substr($color, 1);
}
if (strlen($color) == 6) {
list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
} elseif (strlen($color) == 3) {
list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
} else {
return false;
}
$r = hexdec($r);
$g = hexdec($g);
$b = hexdec($b);
return array($r, $g, $b);
}
}
define your DIR_IMAGE like this way at your model
define('DIR_IMAGE', FCPATH.'image/catalog/');
I dont think you schould use define like that. if you use a constant in a class you schould define it like this:
class MyClass
{
const MYCONSTANT = 'constant value';
function showConstant() {
echo self::MYCONSTANT. "\n";
}
}
Also i would recomand if you use a namespace capable php version to take a look at: http://php.net/manual/en/function.define.php
it is namespace defined, and also i am not sure if define works inside a class... tht is usualy in procedural code.
Related
Struggling to get the math correct for image cropping, hoping someone else is able to see my issue. It appears to be overshooting the dimensions of the image leaving 1 pixel of the original image on the left of the result.
function thumbnail_create($file, $w, $h, $crop = false, $output_filename = null, $output_dirname = null)
{
list($width, $height) = getimagesize(FILESPATH . $file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width - ($width * abs($r - $w / $h)));
} else {
$height = ceil($height - ($height * abs($r - $w / $h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w / $h > $r) {
$newwidth = $h * $r;
$newheight = $h;
} else {
$newheight = $w / $r;
$newwidth = $w;
}
}
$mime = mime_content_type(FILESPATH . $file);
$handler = "imagepng";
if (in_array($mime, ["image/gif"])) {
$src = imagecreatefromgif(FILESPATH . $file);
$handler = "imagegif";
} elseif (in_array($mime, ["image/jpeg", "image/pjpeg", "image/jpeg", "image/pjpeg"])) {
$src = imagecreatefromjpeg(FILESPATH . $file);
$handler = "imagejpeg";
} elseif (in_array($mime, ["image/png"])) {
$src = imagecreatefrompng(FILESPATH . $file);
}
if (!isset($src) || !$src) {
return false;
}
$newImage = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if (!empty($output_dirname)) {
make_dir($output_dirname);
}
// BUILD OUTPUT PATH/FILE
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (empty($output_filename)) {
$output_filename = str_replace("." . $ext, '-thumb.' . $ext, basename($file));
}
if (empty($output_dirname)) {
$output_dirname = dirname($file);
}
$output = $output_dirname . '/' . $output_filename;
$handler($newImage, FILESPATH . $output);
return $output;
}
thumbnail_create('news/feature/fluffy-kitty.png, 100, 100, true)
Before:
After:
Original width: int(862)
Original height: int(192)
Cropped width: float(-2146)
Cropped height: int(192)
I have a problem about resize image at hosting.
When i use function to resize image in Localhost, it's good.
But when i upload them to Cpanel. It's only work with small size picture. With bigger size(maybe 300kb), it doesn't work and doesn't
show any errors. How to fix it?
Please help me!
Command :
resize_image('max',"upload/tindang/".$Hinh,"upload/tindang/".$Hinh,600,600);
This is my function :
function resize_image_crop($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $width / $w;
$new_w = $width;
$new_h = $h * $ratio;
//if that created an image smaller than what we wanted, try the other way
if ($new_h < $height) {
$ratio = $height / $h;
$new_h = $height;
$new_w = $w * $ratio;
}
$image2 = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//check to see if cropping needs to happen
if (($new_h != $height) || ($new_w != $width)) {
$image3 = imagecreatetruecolor ($width, $height);
if ($new_h > $height) { //crop vertically
$extra = $new_h - $height;
$x = 0; //source x
$y = round($extra / 2); //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
} else {
$extra = $new_w - $width;
$x = round($extra / 2); //source x
$y = 0; //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
}
imagedestroy($image2);
return $image3;
} else {
return $image2;
}
}
function resize_image_max($image,$max_width,$max_height) {
$w = imagesx($image); //current width
$h = imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
// if (($w <= $max_width) && ($h <= $max_height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $max_width / $w;
$new_w = $max_width;
$new_h = $h * $ratio;
//if that didn't work
if ($new_h > $max_height) {
$ratio = $max_height / $h;
$new_h = $max_height;
$new_w = $w * $ratio;
}
$new_image = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($new_image,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
return $new_image;
}
function resize_image_force($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
$image2 = imagecreatetruecolor ($width, $height);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $width, $height, $w, $h);
return $image2;
}
function resize_image($method,$image_loc,$new_loc,$width,$height) {
if (!is_array(#$GLOBALS['errors'])) { $GLOBALS['errors'] = array(); }
if (!in_array($method,array('force','max','crop'))) { $GLOBALS['errors'][] = 'Invalid method selected.'; }
if (!$image_loc) { $GLOBALS['errors'][] = 'No source image location specified.'; }
else {
if ((substr(strtolower($image_loc),0,7) == 'http://') || (substr(strtolower($image_loc),0,7) == 'https://')) { /*don't check to see if file exists since it's not local*/ }
elseif (!file_exists($image_loc)) { $GLOBALS['errors'][] = 'Image source file does not exist.'; }
$extension = strtolower(substr($image_loc,strrpos($image_loc,'.')));
if (!in_array($extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid source file extension!'; }
}
if (!$new_loc) { $GLOBALS['errors'][] = 'No destination image location specified.'; }
else {
$new_extension = strtolower(substr($new_loc,strrpos($new_loc,'.')));
if (!in_array($new_extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid destination file extension!'; }
}
$width = abs(intval($width));
if (!$width) { $GLOBALS['errors'][] = 'No width specified!'; }
$height = abs(intval($height));
if (!$height) { $GLOBALS['errors'][] = 'No height specified!'; }
if (count($GLOBALS['errors']) > 0) { echo_errors(); return false; }
if (in_array($extension,array('.jpg','.jpeg'))) { $image = #imagecreatefromjpeg($image_loc); }
elseif ($extension == '.png') { $image = #imagecreatefrompng($image_loc); }
elseif ($extension == '.gif') { $image = #imagecreatefromgif($image_loc); }
elseif ($extension == '.bmp') { $image = #imagecreatefromwbmp($image_loc); }
if (!$image) { $GLOBALS['errors'][] = 'Image could not be generated!'; }
else {
$current_width = imagesx($image);
$current_height = imagesy($image);
if ((!$current_width) || (!$current_height)) { $GLOBALS['errors'][] = 'Generated image has invalid dimensions!'; }
}
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
if ($method == 'force') { $new_image = resize_image_force($image,$width,$height); }
elseif ($method == 'max') { $new_image = resize_image_max($image,$width,$height); }
elseif ($method == 'crop') { $new_image = resize_image_crop($image,$width,$height); }
if ((!$new_image) && (count($GLOBALS['errors'] == 0))) { $GLOBALS['errors'][] = 'New image could not be generated!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
$save_error = false;
if (in_array($extension,array('.jpg','.jpeg'))) { imagejpeg($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.png') { imagepng($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.gif') { imagegif($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.bmp') { imagewbmp($new_image,$new_loc) or ($save_error = true); }
if ($save_error) { $GLOBALS['errors'][] = 'New image could not be saved!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); #imagedestroy($new_image); echo_errors(); return false; }
imagedestroy($image);
imagedestroy($new_image);
return true;
}
i am using opencart 2.1.x version of opencart and i am facing an issue with images in displaying the images.
But image resize function adding Noise in background. It can be seen as in below image::
Tilt the laptop screen or desktop scree to observe noise
Function to resize the image is:
catalog/model/tool/image.php
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename)) {
return;
}
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$old_image = $filename;
$new_image = 'cache/' . utf8_substr($filename, 0,
utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.'.$extension;
list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $old_image);
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $new_image);
} else {
copy(DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
}
system/library/image.php
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->width || !$this->height) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->width;
$scale_h = $height / $this->height;
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->mime != 'image/png') {
return;
}
$new_width = (int)($this->width * $scale);
$new_height = (int)($this->height * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if ($this->mime == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width,
$new_height, $this->width, $this->height);
imagedestroy($image_old);
$this->width = $width;
$this->height = $height;
}
Please assist i ngetting rid from background noise.
It looks like your catalog/model/tool/image.php code snippet is incomplete.
I solved this issue by commenting main part of a function code and returning the path to initial image (OpenCart 2.3.0.2):
<?php
class ModelToolImage extends Model {
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
return;
}
/*$extension = pathinfo($filename, PATHINFO_EXTENSION);
$image_old = $filename;
$image_new = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;
if (!is_file(DIR_IMAGE . $image_new) || (filectime(DIR_IMAGE . $image_old) > filectime(DIR_IMAGE . $image_new))) {
list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);
if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
return DIR_IMAGE . $image_old;
}
$path = '';
$directories = explode('/', dirname($image_new));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_IMAGE . $path)) {
#mkdir(DIR_IMAGE . $path, 0777);
}
}
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $image_old);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $image_new);
} else {
copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
}
}
$image_new = str_replace(' ', '%20', $image_new); // fix bug when attach image on email (gmail.com). it is automatic changing space " " to +
if ($this->request->server['HTTPS']) {
return $this->config->get('config_ssl') . 'image/' . $image_new;
} else {
return $this->config->get('config_url') . 'image/' . $image_new;
}*/
return 'image/' . $filename;
}
}
Have You tried by changing quality to 100 on function save in parameter
public function save($file, $quality = 100) {
$info = pathinfo($file);
$extension = strtolower($info['extension']);
if (is_resource($this->image)) {
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($this->image, $file, $quality);
} elseif ($extension == 'png') {
imagepng($this->image, $file);
} elseif ($extension == 'gif') {
imagegif($this->image, $file);
}
imagedestroy($this->image);
}
}
i am trying to re size the uploading image and moving to a folder, i try with the blow code, but it is not work. i created a function for re sizing the photo, calling that function from another function, but image is not re sized, and photo is not moved to folder.
$final_save_dir = 'techpic';
$thumbname = $_FILES['tpic']['name'];
$imgName = $final_save_dir . '/' . $_FILES['tpic']['name'];
if(#move_uploaded_file($_FILES['tpic']['tmp_name'], $final_save_dir . '/' . $_FILES['tpic']['name']))
{
$this->createThumbnail($thumbname,"600","600",$final_save_dir,$final_save_dir);
}
function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
$path = $uploadDir . '/' . $image_name;
$mime = getimagesize($path);
if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if($old_x > $old_y)
{
$thumb_w = $new_width;
$thumb_h = $old_y*($new_height/$old_x);
}
if($old_x < $old_y)
{
$thumb_w = $old_x*($new_width/$old_y);
$thumb_h = $new_height;
}
if($old_x == $old_y)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// New save location
$new_thumb_loc = $moveToDir . $image_name;
if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
imagedestroy($dst_img);
imagedestroy($src_img);
return $result;
}
function img($field = 'image', $width = null, $height = null, $crop = false, $alt = null, $turl = null) {
global $editormode;
$val = $field;
if (!$val)
$val = 'no-image.png';
$alt = ($alt) ? $alt : stem(basename($val));
if ($width == null && $height == null)
$imgf = get_dir() . $val;
else
$imgf = gen_img($val, $width, $height, $crop);
if (!$imgf)
return "";
$url = $imgf;
if (!$turl)
return "<img src='$url' alt='$alt'/>\n";
else
return "<a href='$turl'><img src='$url' alt='$alt'/></a>";
}
function get_dir() {
return "upload/";
}
function gen_img($fileval, $width, $height, $crop) {
if (!$fileval)
return null;
$fname = get_dir() . $fileval;
if (!is_readable($fname))
return null;
$stem = stem(basename($fname));
if ($width != null && $height != null) {
$sz = getimagesize($fname);
if ($sz[0] == $width && $sz[1] == $height) {
return substr($fname, strlen(UPLOADROOT));
}
$sep = ($crop) ? '__' : '_';
$outname = thumb_dir($fname) . $stem . $sep . $width . "x" . $height . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $height, $crop);
}
else if ($width != null && $height == null) {
$outname = thumb_dir($fname) . $stem . "_" . $width . "." . suffix($fname);
if (!is_readable($outname) || filemtime($outname) < filemtime($fname))
createthumb($fname, $outname, $width, $crop);
} else
$outname = $fname;
//echo $outname; die();
return $outname;
}
function thumb_dir($path) {
$enddir = strrpos($path, "/");
$dir = substr($path, 0, $enddir) . "/.thumbnails/";
if (!file_exists($dir))
mkdir($dir, 0777, true);
return $dir;
}
function createthumb($source, $dest, $new_w, $new_h = null, $crop = false) {
if (!file_exists($source))
return null;
$src_img = 0;
$src_img = image_create($source);
$old_w = imageSX($src_img);
$old_h = imageSY($src_img);
$x = $y = 0;
if ($new_h == null) { // we want a square thumb, cropped if necessary
if ($old_w > $old_h) {
$x = ceil(($old_w - $old_h) / 2);
$old_w = $old_h;
} else if ($old_h > $old_w) {
$y = ceil(($old_h - $old_w) / 2);
$old_h = $old_w;
}
$thumb_w = $thumb_h = $new_w;
} else if ($crop) {
$thumb_w = $new_w;
$thumb_h = $new_h;
$oar = $old_w / $old_h;
$nar = $new_w / $new_h;
if ($oar < $nar) {
$y = ($old_h - $old_h * $oar / $nar) / 2;
$old_h = ($old_h * $oar / $nar);
} else {
$x = ($old_w - $old_w * $nar / $oar) / 2;
$old_w = ($old_w * $nar / $oar);
}
} else if ($new_w * $old_h / $old_w <= $new_h) { // retain aspect ratio, limit by new_w
$thumb_h = $new_w * $old_h / $old_w;
$thumb_w = $new_w;
} else { // retain aspect ratio, limit by new_h
$thumb_w = $new_h * $old_w / $old_h;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecolortransparent($dst_img, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
imagecopyresampled($dst_img, $src_img, 0, 0, $x, $y, $thumb_w, $thumb_h, $old_w, $old_h);
image_save($dst_img, $dest);
imagedestroy($dst_img);
imagedestroy($src_img);
}
function image_create($source) {
$suf = strtolower(suffix($source));
if ($source == '.jpg')
mylog("wtf", "source: $source", true);
if ($suf == "png")
return imagecreatefrompng($source);
else if ($suf == "jpg" || $suf == "jpeg")
return imagecreatefromjpeg($source);
else if ($suf == "gif")
return imagecreatefromgif($source);
return null;
}
function image_save($dst_img, $dest) {
$suf = strtolower(suffix($dest));
if ($suf == "png")
imagepng($dst_img, $dest);
else if ($suf == "jpg" || $suf == "jpeg")
imagejpeg($dst_img, $dest);
else if ($suf == "gif")
imagegif($dst_img, $dest);
}
This your function which is put in your function file
that function has make Folder in the thumbnails in the image folder when you call the function file.
Following way to call the function when image display.
<?php echo img('pages/sample_image.jpg', 122, 81, TRUE) ?>
Here the first is path of the image and 122:means width and 81:height and True/false True:crop the image and false: only resize the image.
And define the Uploadroot in your config file this path for the image folder.
Hope this works.
Thanks.
For resizing an image in php you can use Imagick::resizeImage from this article or use this article
Of course we can use Gd library which has low overhead by recommendation of #CD001. You can find explanation of GD re sizing in this article
Edit for More Explanation
for using Imagick::resizeImage you should see this description
here is the prototype of the function:
bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
Parameters
columns
Width of the image
rows
Height of the image
filter
Refer to the list of filter constants.
blur
The blur factor where > 1 is blurry, < 1 is sharp.
bestfit
Optional fit parameter.
If you want to use gd library here is simple source code
<?php
// File and new size
//the original image has 800x600
$filename = 'images/picture.jpg';
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output and free memory
//the resized image will be 400x300
imagejpeg($thumb);
imagedestroy($thumb);
why is the output image bigger than input using imagick?
original jpg: http://www.persunmall.com/images/jm3.jpg
/**
* example
--------------------------------------
'jm3.jpg' => 119 k (453*680)
'l.jpg' => 275 k (400*600) // why the output jpg is much bigger than input jpg?
*/
$jy_image=new jy_image
$jy_image->output_image('jm3.jpg','l.jpg',400,0);
class bellow:
<?php
class jy_image {
private $image = null;
private $type = null;
// 构造函数
public function __construct() {
}
// 析构函数
public function __destruct() {
if ($this->image !== null)
$this->image->destroy();
}
// 载入图像
public function open($path) {
$this->image = new Imagick($path);
if ($this->image) {
$this->type = strtolower($this->image->getImageFormat()); // jpeg
}
return $this->image;
}
public function crop($x = 0, $y = 0, $width = null, $height = null) {
if ($width == null)
$width = $this->image->getImageWidth() - $x;
if ($height == null)
$height = $this->image->getImageHeight() - $y;
if ($width <= 0 || $height <= 0)
return;
if ($this->type == 'gif') {
$image = $this->image;
$canvas = new Imagick();
$images = $image->coalesceImages();
foreach ($images as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$img->cropImage($width, $height, $x, $y);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
$canvas->setImagePage($width, $height, 0, 0);
}
$image->destroy();
$this->image = $canvas;
} else {
$this->image->cropImage($width, $height, $x, $y);
}
}
/*
* 更改图像大小
$fit: 适应大小方式
'force': 把图片强制变形成 $width X $height 大小
'scale': 按比例在安全框 $width X $height 内缩放图片, 输出缩放后图像大小 不完全等于 $width X $height
'scale_fill': 按比例在安全框 $width X $height 内缩放图片,安全框内没有像素的地方填充色, 使用此参数时可设置背景填充色 $bg_color = array(255,255,255)(红,绿,蓝, 透明度) 透明度(0不透明-127完全透明))
其它: 智能模能 缩放图像并载取图像的中间部分 $width X $height 像素大小
$fit = 'force','scale','scale_fill' 时: 输出完整图像
$fit = 图像方位值 时, 输出指定位置部分图像
字母与图像的对应关系如下:
north_west north north_east
west center east
south_west south south_east
*/
public function resize_to($width = 100, $height = 100, $fit = 'center', $fill_color = array(255, 255, 255, 0)) {
// 保证其中一边,另外一边相应缩放
if($width==0 || $height==0){
$image = $this->image;
$src_width = $image->getImageWidth();
$src_height = $image->getImageHeight();
if($width>0 && $height==0){
$width=($width>$src_width)?$src_width:$width;
$height = $src_height*($width/$src_width);
}
else if($width==0 && $height>0){
$height=($height>$src_height)?$src_height:$height;
$width = $src_width*($height/$src_height);
}
$fit='force';
}
switch ($fit) {
case 'force': // 强制缩放,会变形
if ($this->type == 'gif') {
$image = $this->image;
$canvas = new Imagick();
$images = $image->coalesceImages();
foreach ($images as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$img->thumbnailImage($width, $height, false);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
}
$image->destroy();
$this->image = $canvas;
} else {
$this->image->thumbnailImage($width, $height, false);
}
break;
case 'scale':
if ($this->type == 'gif') {
$image = $this->image;
$images = $image->coalesceImages();
$canvas = new Imagick();
foreach ($images as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$img->thumbnailImage($width, $height, true);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
}
$image->destroy();
$this->image = $canvas;
} else {
$this->image->thumbnailImage($width, $height, true);
}
break;
case 'scale_fill': // 填充白色
$size = $this->image->getImagePage();
$src_width = $size['width'];
$src_height = $size['height'];
$x = 0;
$y = 0;
$dst_width = $width;
$dst_height = $height;
if ($src_width * $height > $src_height * $width) {
$dst_height = intval($width * $src_height / $src_width);
$y = intval(($height - $dst_height) / 2);
} else {
$dst_width = intval($height * $src_width / $src_height);
$x = intval(($width - $dst_width) / 2);
}
$image = $this->image;
$canvas = new Imagick();
$color = 'rgba(' . $fill_color[0] . ',' . $fill_color[1] . ',' . $fill_color[2] . ',' . $fill_color[3] . ')';
if ($this->type == 'gif') {
$images = $image->coalesceImages();
foreach ($images as $frame) {
$frame->thumbnailImage($width, $height, true);
$draw = new ImagickDraw();
$draw->composite($frame->getImageCompose(), $x, $y, $dst_width, $dst_height, $frame);
$img = new Imagick();
$img->newImage($width, $height, $color, 'gif');
$img->drawImage($draw);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
$canvas->setImagePage($width, $height, 0, 0);
}
} else {
$image->thumbnailImage($width, $height, true);
$draw = new ImagickDraw();
$draw->composite($image->getImageCompose(), $x, $y, $dst_width, $dst_height, $image);
$canvas->newImage($width, $height, $color, $this->get_type());
$canvas->drawImage($draw);
$canvas->setImagePage($width, $height, 0, 0);
}
$image->destroy();
$this->image = $canvas;
break;
default:
$size = $this->image->getImagePage();
$src_width = $size['width'];
$src_height = $size['height'];
$crop_x = 0;
$crop_y = 0;
$crop_w = $src_width;
$crop_h = $src_height;
if ($src_width * $height > $src_height * $width) {
$crop_w = intval($src_height * $width / $height); // 100*50 =>50*100 输出:25*50
} else {
$crop_h = intval($src_width * $height / $width); //50*100 =>100*50 输出:50*25
}
switch ($fit) {
case 'north_west':
$crop_x = 0;
$crop_y = 0;
break;
case 'north':
$crop_x = intval(($src_width - $crop_w) / 2);
$crop_y = 0;
break;
case 'north_east':
$crop_x = $src_width - $crop_w;
$crop_y = 0;
break;
case 'west':
$crop_x = 0;
$crop_y = intval(($src_height - $crop_h) / 2);
break;
case 'center':
$crop_x = intval(($src_width - $crop_w) / 2);
$crop_y = intval(($src_height - $crop_h) / 2);
break;
case 'east':
$crop_x = $src_width - $crop_w;
$crop_y = intval(($src_height - $crop_h) / 2);
break;
case 'south_west':
$crop_x = 0;
$crop_y = $src_height - $crop_h;
break;
case 'south':
$crop_x = intval(($src_width - $crop_w) / 2);
$crop_y = $src_height - $crop_h;
break;
case 'south_east':
$crop_x = $src_width - $crop_w;
$crop_y = $src_height - $crop_h;
break;
default:
$crop_x = intval(($src_width - $crop_w) / 2);
$crop_y = intval(($src_height - $crop_h) / 2);
}
$image = $this->image;
$canvas = new Imagick();
if ($this->type == 'gif') {
$images = $image->coalesceImages();
foreach ($images as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$img->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
$img->thumbnailImage($width, $height, true);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
$canvas->setImagePage($width, $height, 0, 0);
}
} else {
$image->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
$image->thumbnailImage($width, $height, true);
$canvas->addImage($image);
$canvas->setImagePage($width, $height, 0, 0);
}
$image->destroy();
$this->image = $canvas;
}
}
// 添加水印图片
public function add_watermark($path, $x = 0, $y = 0) {
$watermark = new Imagick($path);
// 默认水印位置 by jimmy 2014-4-11
if(empty($x) && empty($y)){
$im_w= $this->image->getImageWidth();
$im_h = $this->image->getImageHeight();
$wa_w = $watermark->getImageWidth();
$wa_h = $watermark->getImageHeight();
$x=($im_w-$wa_w)/2;
$y=($im_h-$wa_h-50);
}
$draw = new ImagickDraw();
$draw->composite($watermark->getImageCompose(), $x, $y, $watermark->getImageWidth(), $watermark->getimageheight(), $watermark);
if ($this->type == 'gif') {
$image = $this->image;
$canvas = new Imagick();
$images = $image->coalesceImages();
foreach ($image as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$img->drawImage($draw);
$canvas->addImage($img);
$canvas->setImageDelay($img->getImageDelay());
}
$image->destroy();
$this->image = $canvas;
} else {
$this->image->drawImage($draw);
}
}
// 添加水印文字
public function add_text($text, $x = 0, $y = 0, $angle = 0, $style = array()) {
$draw = new ImagickDraw();
if (isset($style['font']))
$draw->setFont($style['font']);
if (isset($style['font_size']))
$draw->setFontSize($style['font_size']);
if (isset($style['fill_color']))
$draw->setFillColor($style['fill_color']);
if (isset($style['under_color']))
$draw->setTextUnderColor($style['under_color']);
if ($this->type == 'gif') {
foreach ($this->image as $frame) {
$frame->annotateImage($draw, $x, $y, $angle, $text);
}
} else {
$this->image->annotateImage($draw, $x, $y, $angle, $text);
}
}
// 保存到指定路径
public function save_to($path) {
$this->image->stripImage();
if ($this->type == 'gif') {
$this->image->writeImages($path, true);
} else {
$this->image->writeImage($path);
}
}
// 输出图像
public function output($header = true) {
if ($header)
header('Content-type: ' . $this->type);
echo $this->image->getImagesBlob();
}
public function get_width() {
$size = $this->image->getImagePage();
return $size['width'];
}
public function get_height() {
$size = $this->image->getImagePage();
return $size['height'];
}
// 设置图像类型, 默认与源类型一致
public function set_type($type = 'png') {
$this->type = $type;
$this->image->setImageFormat($type);
}
// 获取源图像类型
public function get_type() {
return $this->type;
}
// 当前对象是否为图片
public function is_image() {
if ($this->image)
return true;
else
return false;
}
public function thumbnail($width = 100, $height = 100, $fit = true) {
$this->image->thumbnailImage($width, $height, $fit);
} // 生成缩略图 $fit为真时将保持比例并在安全框 $width X $height 内生成缩略图片
/*
添加一个边框
$width: 左右边框宽度
$height: 上下边框宽度
$color: 颜色: RGB 颜色 'rgb(255,0,0)' 或 16进制颜色 '#FF0000' 或颜色单词 'white'/'red'...
*/
public function border($width, $height, $color = 'rgb(220, 220, 220)') {
$color = new ImagickPixel();
$color->setColor($color);
$this->image->borderImage($color, $width, $height);
}
public function blur($radius, $sigma) {
$this->image->blurImage($radius, $sigma);
} // 模糊
public function gaussian_blur($radius, $sigma) {
$this->image->gaussianBlurImage($radius, $sigma);
} // 高斯模糊
public function motion_blur($radius, $sigma, $angle) {
$this->image->motionBlurImage($radius, $sigma, $angle);
} // 运动模糊
public function radial_blur($radius) {
$this->image->radialBlurImage($radius);
} // 径向模糊
public function add_noise($type = null) {
$this->image->addNoiseImage($type == null ? imagick::NOISE_IMPULSE : $type);
} // 添加噪点
public function level($black_point, $gamma, $white_point) {
$this->image->levelImage($black_point, $gamma, $white_point);
} // 调整色阶
public function modulate($brightness, $saturation, $hue) {
$this->image->modulateImage($brightness, $saturation, $hue);
} // 调整亮度、饱和度、色调
public function charcoal($radius, $sigma) {
$this->image->charcoalImage($radius, $sigma);
} // 素描
public function oil_paint($radius) {
$this->image->oilPaintImage($radius);
} // 油画效果
public function flop() {
$this->image->flopImage();
} // 水平翻转
public function flip() {
$this->image->flipImage();
} // 垂直翻转
/**
* 压缩图片 by jimmy 2014-4-11
* ----------------------------------------
*/
function compress($quality=100){
$this->image->setImageFormat('JPEG');
$this->image->setImageCompression(Imagick::COMPRESSION_JPEG);
$q = $this->image->getImageCompressionQuality();
$q = $q* $quality/100;
if($q==0){
$q = $quality;
}
$this->image->setImageCompressionQuality($q);
$this->image->stripImage();
}
/**
* 综合各个步骤输出 by jimmy 2014-4-11
* ----------------------------------------
*/
function output_image($srcFile,$destFile,$w=0,$h=0,$quality=100,$waterFile='',$fit="scale_fill"){
$this->open($srcFile);
$this->compress($quality);
if(!empty($waterFile)){
$this->add_watermark($waterFile);
}
if($w+$h>0){
$this->resize_to($w,$h,$fit);
}
$this->save_to($destFile);
}
}
First, from your comment "even quality =80 ,the l.jpg is more bigger than jm3.jpg" I think that is wrong. Re-saving the file with lower quality gives the following results.
119,300 = original image
266,008 = Resized at 100%
245,145 = Resized at 100% + despeckle
97,536 = Resized at 90% quality
88,342 = Resized at 90% quality with despeckle
I also added Imagick::despeckle as resizing can introduce speckles.
However the fundamental question you're asking it "Why does re-saving an JPEG image increase the file size, for the same quality?"
The simple answer is that after because it is a lossy format, after saving an image as a JPEG there can be more information in the new image. To save the image at the same quality, that additional information needs encoded, which takes up additional space.
Consider a simple sine wave; it contains very little information. Then imagine that we 'save it as an image' with a lossy format, which trims the ends off the sine wave i.e. something like:
Whichever way you consider the new shape it has more information that needs to be encoded to retain the new shape, so re-saving it at 100% quality takes a lot more space that the original lossy saved image.
Re-saving it at a lower quality produces a smaller image, but rapidly loses information from the image, as each saving is an approximation of an approximation.
TL:DR use PNG for all intermediate formats, and only use JPG for the final output to customers.