I have searched a lot but did not find a working solution.
I have been trying to convert a QRcode SVG file to PNG format.
The following does return an empty black image but with no content. I would like to convert from the SVG format to PNG format with all the contents:
$file = SVG::fromFile(storage_path('app/public/qr_background.svg'));
$background = $file->getDocument();
$qrString = QrCode::size('2500')
->style('round')
->backgroundColor(0,0,0,1)
->generate(
env('FARMCODE_BASE_URL')
? env('FARMCODE_BASE_URL') . $product->id
: route('product-landingpage', ['product' => $product])
);
$qr = SVG::fromString($qrString)->getDocument();
$qr->getChild(1)->setAttribute('transform', "translate(450,450) scale(44)");
$background->addChild($qr);
$name = 'abc.png';
// Make image with Laravel Invervention package
$image = Image::make($file->toRasterImage(2000,2000))->encode('png');
$headers = [
'Content-Type' => 'image/png',
'Content-Disposition' => 'attachment; filename='. $name,
];
return response()->stream(function() use ($image) {
echo $image;
}, 200, $headers);
I am using meyfa/php-svg simplesoftwareio/simple-qrcode and intervention/image
Related
Please, anyone, help me I want to set the Image Resolution to 300dpi for the uploaded image using Image Intervention.
Any alternate solution is also welcome.
What I want:
Upload Image -> Resize image to (100 X 100) -> Set image size to less than 30KB -> and set image resolution to 300dpi -> auto download
I have done everything else the resolution to my project... Here I'm sending the code and link ...
$width = 400;
$height = 200;
$file = $request->file('upload');
$image = Image::make($file)->resize($width, $height)->encode('jpg');
$headers = [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'attachment; filename=utipanpsa_'.$request->type.'.jpg',
];
return response()->stream(function() use ($image) {
echo $image;
}, 200, $headers);
https://www.utipanpsa.com/cropping-tools
acording to document you can use imageresolution() if you have php >= 7.2 like this:
//sets the image resolution to 200
imageresolution($imageRecource, 200);
I'm working with laravel 7 and using intervention/image to store images. However, I want to encode and store images as webp, I'm using the following code but it is not encoding the image in webp rather it is storing in the original format. Can you please tell me what I'm doing wrong?
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$image = Image::make(public_path('uploads/' . $tournament->poster))->encode('webp', 90)->resize(200, 250);
$image->save();
}
}
Try this :
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$classifiedImg = $request->file('poster');
$filename = $classifiedImg->getClientOriginalExtension();
// Intervention
$image = Image::make($classifiedImg)->encode('webp', 90)->resize(200, 250)->save(public_path('uploads/' . $filename . '.webp')
}
}
This is my code to convert to .webp and resize (keep image's ratio)
$imageResize = Image::make($image)->encode('webp', 90);
if ($imageResize->width() > 380){
$imageResize->resize(380, null, function ($constraint) {
$constraint->aspectRatio();
});
}
$destinationPath = public_path('/imgs/covers/');
$imageResize->save($destinationPath.$name);
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
//del old image
unlink($webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
I'm using intervention image on my Lumen project and everything works until I come across on making the encoded image as a downloadable response which upon form submit that contains the image file that will be formatted unto specific format e.g. webp, jpg, png will be sent back as a downloadable file to the user, below is my attempt.
public function image_format(Request $request){
$this->validate($request, [
'image' => 'required|file',
]);
$raw_img = $request->file('image');
$q = (int)$request->input('quality',100);
$f = $request->input('format','jpg');
$img = Image::make($raw_img->getRealPath())->encode('webp',$q);
header('Content-Type: image/webp');
echo $img;
}
but unfortunately, its not my expected output, it just did display the image.
from this post, I use the code and attempt to achieve my objective
public function image_format(Request $request){
$this->validate($request, [
'image' => 'required|file',
]);
$raw_img = $request->file('image');
$q = (int)$request->input('quality',100);
$f = $request->input('format','jpg');
$img = Image::make($raw_img->getRealPath())->encode('webp',$q);
$headers = [
'Content-Type' => 'image/webp',
'Content-Disposition' => 'attachment; filename='. $raw_img->getClientOriginalName().'.webp',
];
$response = new BinaryFileResponse($img, 200 , $headers);
return $response;
}
but its not working, instead it showed me this error
any help, ideas please?
In Laravel you could use the response()->stream(), however, as mentioned in the comments, Lumen doesn't have a stream method on the response. That being said the stream() method is pretty much just a wrapper to return a new instance of StreamedResponse (which should already be included in your dependencies).
Therefore, something like the following should work for you:
$raw_img = $request->file('image');
$q = (int)$request->input('quality', 100);
$f = $request->input('format', 'jpg');
$img = Image::make($raw_img->getRealPath())->encode($f, $q);
return new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($img) {
echo $img;
}, 200, [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'attachment; filename=' . 'image.' . $f,
]);
loading pdf file from php form
$name = $_FILES['file']['name'];
$fileName = substr($_FILES['file']['tmp_name'], 5).".".$ext;
date_default_timezone_set('UTC');
$fileDate = date('d.m.Y');
$fileSize = $_FILES['file']['size'];
$folder = $_POST['folder'];
$target_dir="$media_dir/";
$target_file= $target_dir . basename($_FILES["file"]["name"]);
Move file from tmp to media path
move_uploaded_file($_FILES['file']['tmp_name'], $target_file);
converting pdf to jpg using Imagick
$imagick = new imagick();
$imagick->readImage($target_file);
$imagick->setImageFormat('jpg');
$image= basename($target_file,".pdf");
foreach($imagick as $i=>$imagick)
{
$imagick->writeImage($target_dir . $image . ($i+1) ." of ". $pages.".jpg");
} $imagick->clear();
How can I save the converted image to a database. Currently, it is just uploading the original pdf image to the database.
$id_object = _addMediaFile($name, $fileName, 2, $fileSize, $folder);
$ret = array("ID" => $id_object, "name" => $name, "fileName" => $fileName, "fileSize" => $fileSize, "fileDate" => $fileDate, "fileType" => 4, "folder" => $folder);
echo json_encode($ret);
}
Consider converting the image directly into a blob that you directly save into a database column of blob type. For instance, with $a = $image->getImageBlob(); you would save $a into the database. Reference: http://php.net/manual/en/imagick.getimageblob.php
I want to upload a resized image to Amazon S3 bucket, using Yii framework, but to do it directly -- without uploading original (not resized) image to any folder, anywhere within Yii, website or server structure.
I have used ThumbsGen extension to create thumbnail of an image. The code works, if I upload file on my own server. But, if I upload the image to S3, then it will not create a thumbnail.
My code is look like this:
<?php
Yii::app()->setComponents(array('ThumbsGen' => array(
'class' => 'ext.ThumbsGen.ThumbsGen',
'thumbWidth' => Yii::t('constants', 'SECRETCODE_WIDTH'),
'thumbHeight' => Yii::t('constants', 'SECRETCODE_HEIGHT'),
'baseSourceDir' => Yii::app()->request->s3baseUrl.'/uploads/secretcode/original/',
'baseDestDir' => Yii::app()->request->s3baseUrl. '/uploads/secretcode/thumbs/',
'postFixThumbName' => null,
'nameImages' => array('*'),
'recreate' => false,
)));
class SecretCodeController extends MyController {
public function actionCreate() {
$model = new SecretCode;
$model->scenario = 'create';
if (isset($_POST['SecretCode'])) {
$model->attributes = $_POST['SecretCode'];
$temp = $model->promo_image = CUploadedFile::getInstance($model, 'promo_image');
if ($model->validate()) {
$rnd = rand(1, 1000);
$ext = $model->promo_image->extensionName;
$filename = 'secret_' . Yii::app()->user->app_id . '_' . time() . '_' . $rnd . '.' . $ext; $success = Yii::app()->s3->upload( $temp->tempName , 'uploads/secretcode/original/'.$filename);
if(!$success)
{
$model->addError('promo_image', Yii::t('constants', 'IMAGE_FAILURE'));
} else {
$model->promo_image = $filename; $model->promo_image = $filename;
$fullImgSource = #Yii::app()->s3->getObject(Yii::app()->params->s3bucket_name,"uploads/secretcode/original/".$filename);
list($width, $height, $type, $attr) = getimagesize($fullImgSource->headers['size']);
$dimensions = array();
$dimensions = CommonFunctions :: SetImageDimensions($width, $height,Yii::t('constants', 'SECRETCODE_WIDTH'), Yii::t('constants', 'SECRETCODE_HEIGHT'));
Yii::app()->ThumbsGen->thumbWidth = $dimensions['width'];
Yii::app()->ThumbsGen->thumbHeight = $dimensions['height'];
Yii::app()->ThumbsGen->createThumbnails();
}
if ($model->save()) {
Yii::app()->user->setFlash('success', Yii::t('constants', 'Secret Code')." ". Yii::t('constants', 'ADD_SUCCESS'));
$this->redirect(array('create'));
}
}
}
}
$this->render('create', array(
'model' => $model,
));
}
}
As a result, I'm getting a PHP warning:
getimagesize(42368) [<a href='function.getimagesize'>function.getimagesize</a>]: failed to open stream: No such file or directory
What am I doing wrong?
getimagesize — Get the size of an image
array getimagesize ( string $filename [, array &$imageinfo ] )
Your code:
list($width, $height, $type, $attr) = getimagesize($fullImgSource->headers['size']);
$fullImgSource->headers['size'] - I doubt that it stores the file path to image;
try this:
list($width, $height, $type, $attr) = $fullImgSource->headers['size'];
or
list($width, $height, $type, $attr) = getimagesize(/*path to image*/);
Can also read Transferring Files To and From Amazon S3