I am able to upload my images ok, I am able to create thumbnails ok, but only the first thumbnail is being uploaded. I checked the error code for the resize function and they all say 'true' (Success). However, if I upload 4 files, only the first is being uploaded to the thumbnail folder. Here is my code:
function _upload_them_images($_FILES, $last_insert_id)
{
$error = '';
// for($i=0; $i<count($_FILES); $i++)
for($i=0; $i<count($_FILES['imagefile']['name']); $i++)
{
$_FILES['userfile']['name'] = $_FILES['imagefile']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['imagefile']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['imagefile']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['imagefile']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['imagefile']['size'][$i];
$config['file_name'] = $last_insert_id.'_'.time().rand(1000,9999).$i;
$config['upload_path'] = './images/vehicles/';
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '1000';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
if($this->upload->do_upload())
{
$upload_result = $this->upload->data();
$rc = $this->_image_name_into_database(
$last_insert_id,
$upload_result['file_name']);
$image_config = array(
'source_image' =>$upload_result['full_path'],
'new_image' => './images/vehicles/thumbs/',
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 75,
'height' => 50
);
$this->load->library('image_lib', $image_config);
$resize_rc = $this->image_lib->resize();
$error += 0;
}
else
{
//if the image was not uploaded successfully, try resizing
$error += 1;
}
}
if($error > 0)
{
return FALSE;
}
else
{
return TRUE;
}
}
Your image library parameters aren't being updated in the loop. When you call $this->load->...., duplicate items are ignored. You should instead re-initialize the image library with:
$this->image_lib->clear();
$this->image_lib->initialize($image_config);
Before each ->resize()
Related
I am trying to figure out how to resize an image on upload with symfony 5. Actually my fileupload is working perfectly, but it would be such a relief not to resize all my pics before I have to upload them.
Is there a way I can do this?
Here is my upload code:
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
#CAN'T RESIZE HERE BEFORE UPLOAD ???
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
#.....persist - flush etc.
}
First this is my controller with a method to upload an image from a form:
/**
* #Route("/admin/image/new", name="admin_image_new")
*/
public function newImage(Request $request, EntityManagerInterface $manager, FileUploader $fileUploader, ImageResizeService $imageResize)
{
$image = new Image();
$form = $this->createForm(ImageType::class, $image);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
$manager->persist($image);
$manager->flush();
$this->addFlash('success', 'Image added successfully !');
$imageName = $image->getFilename();
$fullSizeImgWebPath = $fileUploader->getTargetDirectory().'/'.$imageName;
[$width,$height] = getimagesize($fullSizeImgWebPath);
if($width > $height){
$width = 1500;
$height = 1000;
// $imageResize->writeThumbnail($fullSizeImgWebPath, 1500, 1000);
} else if($width == $height){
$width = 300;
$height = 300;
//$imageResize->writeThumbnail($fullSizeImgWebPath, 300, 300);
} else {
$width = 1500;
$height = 2254;
//$imageResize->writeThumbnail($fullSizeImgWebPath,1000,1600);
}
$imageResize->writeThumbnail($fullSizeImgWebPath, $width, $height);
return $this->redirectToRoute('admin_image');
}
return $this->render('admin/image/new_image.html.twig', [
'controller_name' => 'AdminImageController',
'form'=> $form->createView()
]);
}
I created a service to resize the uploaded image:
class ImageResizeService {
/**
* Write a thumbnail image using Imagine
*
* #param string $thumbAbsPath full absolute path to attachment directory e.g. /var/www/project1/images/thumbs/
*/
public function writeThumbnail($thumbAbsPath, $width, $height) {
$imagine = new Imagine;
$image = $imagine->open($thumbAbsPath);
$size = new Box($width, $height);
$image->thumbnail($size,ImageInterface::THUMBNAIL_OUTBOUND)
->save($thumbAbsPath);
}
}
I've been attempting to resize a image in codeigniter 3 ,but no luck! I have the resize inside the ddoo_upload() function , the resize() will work , when it comes to one image field within that form and if you will add two image field within that form , then the resize() will not work. Not sure what is wrong!
This is what i have tried for image upload,The code below shows my upload function (and resize within it)
if (isset($_FILES['destiimg']) && $_FILES['destiimg']['name'] != '') {
$filename = $this->ddoo_upload('destiimg', '2000' , '336');
} else {
$filename = NULL;
}
if (isset($_FILES['destiimg_thumb']) && $_FILES['destiimg_thumb']['name'] != '') {
$destbannerthumb_imgnew = $this->ddoo_upload('destiimg_thumb', 300 , 225);
} else {
$destbannerthumb_imgnew = NULL;
}
function ddoo_upload($filename, $width, $height)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename)) {
echo $this->upload->display_errors();die();
return NULL;
} else {
$data = $this->upload->data();
$filename = $data['file_name'];
$config1['image_library'] = 'gd2';
$config1['source_image'] = $this->upload->upload_path.$this->upload->file_name;
//$config1['create_thumb'] = TRUE;
$config1['maintain_ratio'] = FALSE;
$config1['width'] = $width;
$config1['height'] = $height;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
return $filename;
}
}
The upload works fine , but the resize has some issue.
You are missing some config options when loading image_lib.
Look at the manual, you didn't specified source_image (and other options).
If you want to use something advanced, there is good library called Image Moo. It's older but good working with CI3.
This is my post controller function. I always upload images less then 200x200, and those images are stored in the 'upload' folder. After uploading the image, the id number is changed to something like 4546464.png. But I want to change the image size to 60x60 when uploading and store it after changing the size and quality to 60x60x30. This code uploads fine but not changing size and quality.
public function actionCreate() {
$model = new Monitor();
if ($model->load(Yii::$app->request->post())) {
if ($model->payment_processor) {
$model->payment_processor = implode(',', $model>payment_processor);
}
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file != '') {
$model->image = time() . '.' . $model->file->extension;
}
$model->update_at = date('Y-m-d h:i:s');
$model->save();
if ($model->file != '') {
$model->file->saveAs('upload/' . $model->image);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', ['model' => $model]);
}
}
, you have to first upload the image in your server then resize it to what size you want , another way is before you
$model->file->saveAs('upload/' . $model->image);
resize it , but i recommend to you save the Original file and then resize it as a copy.
here is function to resize and crop image from center :
public static function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 100){
$quality = 10;
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 9;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 100;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
use this function as easy you can :
yourModel::resize_crop_image(150,150, $path, 'upload/'.$name_you_want_or_random_string.'.jpg',$q);
the $path is a path of the original file that uploaded .
you have to create a upload folder in your web app directory or change destination to where you want .
I am using the imageprocessor extension and I'm very happy with it. You just have to add confgurations to the imageprocessor component and on save you have to call the save method of the component. It will create a new image with the size you've configured. It has a nice documentation. Give it a try.
i have a pragmatically added product in my code , the product is added to presta correctly but not about its image .
here is some part of my code that i used :
$url= "localhost\prestashop\admin7988\Hydrangeas.jpg" ;
$id_productt = $object->id;
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_productt ;
$image->position = Image::getHighestPosition($id_productt) + 1 ;
$image->cover = true; // or false;echo($godyes[$dt][0]['image']);
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (! self::copyImg($id_productt, $image->id, $url, 'products', false))
{
$image->delete();
}
}
but my product have not any image yet
the problem is in copyImg method ...
here is my copyImg function :
function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
{
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity)
{
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_.(int)$id_entity;
break;
}
$url = str_replace(' ' , '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
// Just hide the warning, the traitment will be the same.
if (#copy($url, $tmpfile))
{
ImageManager::resize($tmpfile, $path.'.jpg');
$images_types = ImageType::getImagesTypes($entity);
foreach ($images_types as $image_type)
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'],
$image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
else
{
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
can anybody help me ?
You have 2 issues:
You are passing 5th parameter (with value) to copyImg, while the function does not have such.
Your foreach ($images_types as $image_type) loop must include the Hook as well (add open/close curly braces).
foreach ($images_types as $image_type)
{
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
You should also check if the product is imported correctly, expecially the "link_rewrite" and if the image is phisically uploaded in the /img/ folder.
I am abel to add image programmatically. But images are not getting resized. In other words resized images are not generating. Attaching the code I use:
$image = new Image();
$image_url = 'http://i.imgur.com/0zSw2gl.jpg';
$id_image = Product::getCover($id_product);
$shops = Shop::getShops(true, null, true);
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) + 1;
$image->cover = true; // or false;
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (!AdminImportControllerExtended::copyImgCustom($id_product, $image->id, $image_url, 'products', false))
{
$image->delete();
}
}
Images should be resized programatically
I use this code
$image = new Image();
$image->id_product = (int)$product->id;
$image->position = Image::getHighestPosition($product->id) + 1;
$image->cover = 1;
if (!$image->add())
exit(Tools::jsonEncode(array('error' => Tools::displayError('Error while creating additional image'))));
else
{
$new_path = $image->getPathForCreation();
ImageManager::resize($image_path, $new_path.'.'.$image->image_format);
$images_types = ImageType::getImagesTypes('products');
foreach ($images_types as $image_type)
{
if (!ImageManager::resize($image_path, $new_path.'-'.Tools::stripslashes($image_type['name']).'.'.
$image->image_format, $image_type['width'], $image_type['height'], $image->image_format))
exit(Tools::jsonEncode(array('error' => Tools::displayError('An error occurred while copying image:').
' '.Tools::stripslashes($image_type['name']))));
}
$image->update();
}