How delete exif data in this function? - php

I don't know how delete exif data from uploaded pictures. Here is my function:
$uploadedFiles = $request->getUploadedFiles();
if ($uploadedFiles && $id) {
$usersPath = '/collections/' . date('Y/m') . '/' . $id .'/';
$uploadFolder = realpath(BASE_PATH . '/uploads');
$uploadFolder .= $usersPath;
$newName = md5(time() . serialize($uploadedFiles));
$fileExtension = strtolower($uploadedFiles[0]->getExtension());
$sourceImgPath = $uploadFolder .$newName .'.' .$fileExtension;
if (!file_exists($uploadFolder)) {
mkdir($uploadFolder, 0777, true );
}
if(in_array($fileExtension, array('jpg', 'jpeg', 'png', 'gif'))){
if ($uploadedFiles[0]->moveTo($sourceImgPath)) {
$info = pathinfo($sourceImgPath);
if ($info) {
$file_path = $usersPath . $info['filename'] . '.' . $fileExtension;
(new \Rapid\Storage\CollectionsStorage())->editImage($id, $file_path);
} else {
$session->set('msg_error', $this->translate->_('There was an unexpected error with uploading the file'));
}
}
}
} else {
$session->set('msg_error', $this->translate->_('Invalid file type'));
}

This piece of code should delete all EXIF information in JPEG
$img = new Imagick($uploadfile);
$img->stripImage();
$img->writeImage($uploadfile);

It depends on the graphics libraries you have access to.
If you have access to imagick, you can use stripImage().
If you have only access to gd, you need to create a new image from the upload and save that instead, see for example PHP remove exif data from images for a jpg image.

Related

How to upload Image or large file to temp folder before submit form in laravel

I'm using this code to upload files or images. It's working but can't upload a large file and I want to upload a file when selecting it from the local computer like the below image.
I use below PHP code in the controller.
$image = $request->file('file_upload');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
echo $new_name;
$image->move(public_path('images'), $new_name);
Try to use this code.
Change the $request->sharing_file with your field name.
You can increase the $size for image what you want, currently it is 16mb and working fine.
$myimage = $request->image;
$size = getClientSize();
if($sizes < 16777216){
$fileMimeType = explode('/', $myimage->getClientMimeType());
$fileType = $fileMimeType[0];
$originalFileName = substr($myimage->getClientOriginalName(), 0, strpos($myimage->getClientOriginalName(), "."));
$originalFileName = substr(str_replace(' ', '-', $originalFileName),0,10);
$rand = rand(9,1000);
$fileName = $rand.'-'.$originalFileName.'.'.$myimage->getClientOriginalExtension();
$upload = $values->move(public_path('images'), $fileName);
if($upload) {
$message = 'File Uploaded';
} else {
$message = "Failed to upload file";
}
}
else {
$message = 'Files size should be less than 16 MB.';
}
Try
if ($request->hasFile('file_upload')) {
$destinationPath = public_path().'/images/';
$file = $request->file_upload;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['your_databse_table_field_name'] = $fileName;
}

Laravel Intervention Unable to init from given binary data for WEBP type files

I am trying to upload the binary image to the storage using Laravel Intervention Image but it gives me error as Unable to init from given binary data.
I am using this code
$image = base64_decode($postData['image']);
$destinationPath = storage_path($destinationFolder);
if (!File::exists($destinationPath)) {
File::makeDirectory($destinationPath, 0777, true, true);
}
$filename = ($fileName != '') ? $fileName : $folderName . '_' . time() . '.jpg';
$imageResult = Image::make($image)->resize($imageWidth, $imageHeight, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath . $filename, imageQuality($image));
if ($imageResult){
return '/image/' . $filename;
}
return false;
The binary image data is
data:image/webp;base64,UklGRlIFAABXRUJQVlA4IEYFAAAQHACdASpPAHkAPlEQlEojkdHMYDgFBLIAZqA25eJVGRUWLtSnk7iTzHecd0SXUx8+t+zLWt8WJpEWrTTvLe9y9CX9VSAw3YOVEdn4oGm0ZIrnQUIJ7VsI/r+aW0VOJeFoJylth8MmFQHlbPEklNUVbgyVJnINmgXnDbtgj9paOvkDYnVAdv2ErJONHxXyp2eyn7mB6vcVu9AfWuUtDlYxhQG1CEongtTYR0U4jQIbXYTTzN/3G5cAEd0FmVN272q9XHtEAeWzrMHHsZ7YPtpmppalPe8BvhnrwSA+ctaG9iQ6b7pEVBVPAAD+/uy97OjEKfy53WiZp+vshoaLbmP0cVKb4k6hnKsxJdcP+CgaRYQkOjb4FGLJO55Q/c+afu5UzMOW3Tx4pq6YezZD8PSoPz4zk6GAAEL9XDf3c3RwQKG1r2lWKnBonjqCV8/oU/xr4Gv59y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EDkEBdEl2HLQOA2mSntOQ3dTgMQX/71+MtpetptbThjL/fnRMMfVnpovAe2jd4SXx+s8fMNJXcEkO9ZKxIWFH0EwLvzIp8SPc5z+AzLEwfn4aBvVL835u4BsodI+usLpWnlC7Xdz6JMVxKivRpoWgrcIsAF91564sRuvXd3rwozLc0Fb/at7P3B3B5Jc7wPXQ/CH5Y6Thjn0W8zAWnd3VwwB3ZS/Uv/ubq8H7W9He6fvg6Ib/101yfwV8xpmLHwZGmXWgAAAAAAA=
In addition to using RAUSHAN KUMAR's answer, you can also use InterventionImage like this
Route::get('test', function() {
$image = 'data:image/webp;base64,UklGRlIFAABXRUJQVlA4IEYFAAAQHACdASpPAHkAPlEQlEojkdHMYDgFBLIAZqA25eJVGRUWLtSnk7iTzHecd0SXUx8+t+zLWt8WJpEWrTTvLe9y9CX9VSAw3YOVEdn4oGm0ZIrnQUIJ7VsI/r+aW0VOJeFoJylth8MmFQHlbPEklNUVbgyVJnINmgXnDbtgj9paOvkDYnVAdv2ErJONHxXyp2eyn7mB6vcVu9AfWuUtDlYxhQG1CEongtTYR0U4jQIbXYTTzN/3G5cAEd0FmVN272q9XHtEAeWzrMHHsZ7YPtpmppalPe8BvhnrwSA+ctaG9iQ6b7pEVBVPAAD+/uy97OjEKfy53WiZp+vshoaLbmP0cVKb4k6hnKsxJdcP+CgaRYQkOjb4FGLJO55Q/c+afu5UzMOW3Tx4pq6YezZD8PSoPz4zk6GAAEL9XDf3c3RwQKG1r2lWKnBonjqCV8/oU/xr4Gv59yLHfFPfneUb6BrG9yoc40NAk+xGkgtKGsIDDanX+uuhaKWGntbgweNVylzqaIqZrCMYGgfkbTo+yPQ0JgHev/+hCnqRe4cEi4VfveeAi+7wBLg2w4tZOj0d7O7gJM6Zj9uaLB6l/3xyvdHwzThmi8na5GMB/v+Y7YAIYCGOV62mQ6XSrBMQHKUoPvIVwUeHVkJFWnUCt6S7yOMa9RkZxe8//Bphx4NhJ/dXc3x7HQESKmLUu8nofAJKiyg7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pmLHwZGmXWgAAAAAAA=';
$image = imagecreatefromwebp($image);
return Image::make($image)->resize(100)->response();
});
By calling the route 'test' you will see the image.
As this is a webp type image, so i need to use imagecreatefromwebp() to upload the images. I have written this piece of code for that.
$destinationFolder = 'uploads/';
$folderName = $folder . '_' . $adId;
if ($folderName != '') {
$folderNames = explode('_', $folderName);
$folderPath = implode('/', array_map(function ($value) {
return $value;
}, $folderNames));
$destinationFolder .= $folderPath . '/';
}
$destinationPath = storage_path($destinationFolder);
if (!\File::exists($destinationPath)) \File::makeDirectory($destinationPath, 0777, true, true);
$fileName = $folder . '_' . $adId . '_0_' . time() . '.jpg';
$fileName = ($fileName != '') ? $fileName : $folderName . '_' . time() . '.jpg';
$im = imagecreatefromwebp($data);
$imageResult = imagejpeg($im, $destinationPath . $fileName, 100);
imagedestroy($im);
if ($imageResult) return '/image/' . $fileName;
return "/DefaultImage.jpg";
If you still wants to use your code, you can remove data:image/webp;base64, then use base64_decode after you remove it.
$image=explode(",",$postData['image']);
$image=base64_decode($image['1']);
Image Intervention can decode your base64 image you can try this
$imageResult = Image::make($postData['image'])->resize($imageWidth, $imageHeight, function ($constraint) {
$constraint->aspectRatio();

PHP file upload is creating filenames starting with "PHP" and with .tmp extension

I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');
$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];
$image= new Image();
$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}
I use a class UploadFileMover that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of UploadedFile contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i=1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
This class is instanciated when an image is uploaded. In other words, I have an Entity Image that has a method upload. Inside entity class:
public function upload()
{
if (null === $this->getFile()) {
return;
}
$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);
$this->file = null;
}
I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.
Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.
The problem was created by the line:
$originalName = $file->getFilename();
Use:
$originalName = $file->getClientOriginalName();
instead.

Uploading image to with custom name in Yii framework

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:
//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part
The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?
Well first thing you need to do is to prevent database input if the picture is not saved.
if(isset($uploadedfile))
{
if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
{
$personModel->save();
}
else
{
//throw error
}
}
As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
$upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();
You have to check your folder permission.
The problem has been solved through following code:
$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;
if (isset($uploadFile)) {
$personModel->picture = $fileName;
$uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}

(OpenCart) View Images Uploaded by Customer

I am trying to upload an image from customer product page (upload file option), the image is uploaded to system/upload folder and renamed with: filename + md5 hash string. So, for example I upload image.jpg, the file will be uploaded to system/upload/image.jpg.392da1267fbfa4be65f7859bb0b974d9.
Now I want to see that image uploaded by customer from admin page (I created a new module page), how can I resize and display the image file? I can get the file name from table oc_upload in database, but the phisical file is using modified name which has no extension, I cannot resize this file because it is located in system/upload folder and its extension is changed. The image resize tool can only resize images in image folder with some allowed extensions configured in Settings page.
Any idea how to display images uploaded by customer? Do I need to copy the renamed uploaded file to image folder using its original name and then resize and display it? I appreciate any of your ideas. Thank you.
Just got the solution by copying the resize() method in admin/model/tool/image.php to my controller and modify it to resize image from system/upload folder.
private function resizeImageUpload($old_filename, $width, $height, $new_filename = '') {
$extension_arr = array('jpeg', 'jpg', 'png', 'gif');
$old_image = $old_filename;
if (!empty($new_filename)) {
$extension = pathinfo($new_filename, PATHINFO_EXTENSION);
$new_image = 'cache/system/upload/' . utf8_substr($new_filename, 0, utf8_strrpos($new_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
} else {
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = 'cache/system/upload/' . utf8_substr($old_filename, 0, utf8_strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
}
if (!in_array($extension, $extension_arr)) return '';
if (!is_file(DIR_IMAGE . $new_image) || (filectime(DIR_UPLOAD . $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_UPLOAD . $old_image);
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_UPLOAD . $old_image);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $new_image);
} else {
$success = copy(DIR_UPLOAD . $old_image, DIR_IMAGE . $new_image);
}
}
if ($this->request->server['HTTPS']) {
return HTTPS_CATALOG . 'image/' . $new_image;
} else {
return HTTP_CATALOG . 'image/' . $new_image;
}
}

Categories