Can I resize an image on upload in symfony 5? - file-upload

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);
}
}

Related

mapbox omnivore cannot parse kml string

Currently, i've getting the string data from the maps.kml to display in laravel blade for simple testing. Based on the official documentation, mapbox can parse the kml string to maps. But it wont displayed.
Controller
...
$excelFile = public_path().'/assets/excel.xlsx';
$kmlfile = public_path(). '/assets/maps.kml';
$kmlContent = file_get_contents($kmlfile);
$kmlLoad = simplexml_load_string($kmlContent);
$kmlJsonFile = $kmlLoad->Document->Folder->Placemark;
// $kmlJson = json_decode($kmlLoad);
$parse = SimpleXLSX::parse($excelFile);
if ($parse) {
$petaSheet = $parse->rows(0, 0); //worksheet index, row limit
foreach($kmlJsonFile as $item)
{
foreach($petaSheet as $peta)
{
if($peta[0] == $item->name)
{
$item->Style->LineStyle->color = $peta[0];
}
}
}
// $monitorSheet = $parse->rows(1, 0);
} else {
$excelRaw = SimpleXLSX::parseError();
}
// $kmlJsonFile = json_encode($kmlJsonFile);
return view('home', [
'peta' => $petaSheet,
'kml' => $kmlContent
]);
Here the js file inside laravel blade
var kmlString = "";
kmlString += `{!! $kml !!}`;
var runLayer = omnivore.kml.parse(kmlString)
.on('ready', function() {
map.fitBounds(runLayer.getBounds());
})
.addTo(map);

How to resize image yii2 when uploading

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.

Image not resizing when added programmatically prestashop

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();
}

How to resize a image while uploading in ZF2

I'm new to Zend Frame work and I need to implement image resize while uploading in zend framework 2. I try to use the method in image resize zf2 but it didnot work for me.
please help?
public function addAction(){
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$width = $this->params('width', 30); // #todo: apply validation!
$height = $this->params('height', 30); // #todo: apply validation!
$imagine = $this->getServiceLocator()->get('my_image_service');
$image = $imagine->open($File['tmp_name']);
$transformation = new \Imagine\Filter\Transformation();
$transformation->thumbnail(new \Imagine\Image\Box($width, $height));
$transformation->apply($image);
$response = $this->getResponse();
$response->setContent($image->get('png'));
$response
->getHeaders()
->addHeaderLine('Content-Transfer-Encoding', 'binary')
->addHeaderLine('Content-Type', 'image/png')
->addHeaderLine('Content-Length', mb_strlen($imageContent));
return $response;
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('./data/tmpuploads/');
if ($adapter->receive($File['name'])) { //identify the uploaded errors
$profile->exchangeArray($form->getData());
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
}
}
}
}
return array('form' => $form);
}
Related to :-image resize zf2
I get answer for this question by adding external library to zend module.It is a easy way for me. i used http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ class as external library.this is my controller class.
class ProfileController extends AbstractActionController{
public function addAction()
{
$form = new ProfileForm();
$request = $this->getRequest();
if ($request->isPost()) {
$profile = new Profile();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge(
$nonFile,
array('fileupload'=> $File['name'])
);
//set data post and file ...
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>100000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
} else {
$adapter->setDestination('//destination for upload the file');
if ($adapter->receive($File['name'])) {
$profile->exchangeArray($form->getData());
//print_r($profile);
echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload;
$image = new SimpleImage();
$image->load('//destination of the uploaded file');
$image->resizeToHeight(500);
$image->save('//destination for where the resized file to be uploaded');
}
}
}
}
return array('form' => $form);
}
}
Related:-Zend Framework 2 - How to use an external library
http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

Codeigniter Multiple file upload and thumbnail creation: only one thumbnail being uploaded

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()