How to show image GD Resource in twig template - image

I have generated a GD Image Resource from the Zend Barcode Object. How can I render this resource in a twig template?

hello this code do the trick :
require 'vendor/autoload.php';
use Zend\Barcode\Barcode;
// Only the text to draw is required
$barcodeOptions = array('text' => 'ZEND-FRAMEWORK');
// No required options
$rendererOptions = array();
$image = Barcode::draw(
'code39',
'image',
$barcodeOptions,
$rendererOptions
);
// By default, imagepng will print on the output file your image.
// Here we play around with ob_* to catch this output and store it on $contents variable.
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
// Save as test.png your current barcode.
file_put_contents('test.png', $contents);
// Display img tag with base64 encoded barcode.
echo '<img src="data:image/png;base64,'.base64_encode($contents).'">';
Explication :
imagejpeg() or imagepng() receive as parameter gd image ressource and print it. Here we play around with ob_*function to capture this output in variable instead of print it. Then you can do what ever you want with this data. On my code i have done both possibility :
Save it in static file.
Directly print it as base64 image inside my html.

Related

How to store image as URL in Laravel 8.*

In my application I add photos that are then scaled, I call them to my views using {{asset()}}
Everything works fine, but for my mobile app I need to send to API URL of image instead of just image path called from db.
That's how I save images now:
$image = $request->photo_patch;
$filename = time() . '.' . $image->extension();
$event->photo_patch = $filename;
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 630);
$image_resize->save('storage/images/' . ($filename));
$event->save();
Example of saved image name:
1630531230.jpg
That's how I get image on view:
<img src="{{ asset('storage/images/' . $eventView->photo_patch) }}">
What I tried:
$url = Storage::url($filename);
$event->photo_patch = $url;
After this file name looks like this
"/storage/1631043493.png"
But that isnt really URL
What can I do to save photo path like this:
"localhost/storage/images/1631043493.png"
Edit:
# Фарид Ахмедов suggested to call whole URL in API.
How can I do that then?
This is what I tried:
Route::get('/events/{id}', function($id){
return [
Event::findOrFail($id),
'image' => asset('storage/images/'.$this->photo_patch)
];
});
That's it.
url(Storage::url($filename));
But I think, you don't need to save the whole path. You can convert it to full URL before sending response.

How can i save data from HTML img tag in laravel

I have a form include image, this image i get from webcam and store it to img tag, how can i save data from attribute src, usually to store file using upload file.
<img id="myImage" src="data:image/png;base64,IvBo9Vraf...." alt="image from snapshot" />
I have read similar questions but not as i expected
With this code you can saved the files.
$filename = $request->file('myFile')->store('files');
$data= new FileModel();
$data->file = $filename;
$data->save();
or you can try below method
$myImage = $request->file('myFile');
if(!in_array($myImage->getMimeType(), ['image/jpeg', 'image/png'])){
abort(500, 'Unsupported Image Type');
}
$imageName = str_replace('myImages/', '', $myImage->store('myFile'));
return ['my_image'=>$profile_picture_name];

Converting html to pdf after clicking on download button in codeigniter

I have created a resume builder application.User enters all required details and i am storing all details in database. Then i am fetching those records and displaying it in different templates. I have created 3 templates. Now I want to give download as pdf and download as docx two download buttons. Once user clicks on any of buttons file will be downloaded in their chosen format. Either pdf or docx.
Is it possible to achieve in codeigniter?
i used Tcpdf
Controller Code is
the code written in controller download $this - > load - > library("Pdf");
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set auto page breaks
$pdf - > SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf - > setImageScale(PDF_IMAGE_SCALE_RATIO);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf - > AddPage();
// Set some content to print
$html = $this - > load - > view('resume/res_template1_view', array('left_sidebar' => 'sidebar/left_sidebar', ' right_sidebar' => 'sidebar/right_sidebar'), $data, TRUE);
// Print text using writeHTMLCell()
$pdf - > writeHTML($html, 0, 0, '', '', 0, 1, 0, true, '', true);
//$pdf->writeHTML($html, true, false, true, false, '');
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf - > Output('resume.pdf', 'D');
Probably you need to use some library in CI to achieve this. Please check below.
you can use Html2Pdf for CI3 library. https://github.com/shyamshingadiya/HTML2PDF-CI3
How to Use
There are 4 options you a required to set in order to create a PDF; folder, filename, paper and HTML
//Load the library
$this->load->library('html2pdf');
//Set folder to save PDF to
$this->html2pdf->folder('./assets/pdfs/');
//Set the filename to save/download as
$this->html2pdf->filename('test.pdf');
//Set the paper defaults
$this->html2pdf->paper('a4', 'portrait');
//Load html view
$this->html2pdf->html(<h1>Some Title</h1><p>Some content in here</p>);
The create function has two options 'save' and 'download'. Save will just write the PDF to the folder you choose in the settings. Download will force the PDF to download in the clients browser.
//Create the PDF
$this->html2pdf->create('save');
Advanced usage
Theres no reason why you can't build and pass a view to the html() function. Also note the create() function will return the saved path if you choose the 'save' option.
$data = array(
'title' => 'PDF Created',
'message' => 'Hello World!'
);
//Load html view
$this->html2pdf->html($this->load->view('pdf', $data, true));
if($path = $this->html2pdf->create('save')) {
//PDF was successfully saved or downloaded
echo 'PDF saved to: ' . $path;
}
Please check above mentioned solution. Let me know if it not works.

PHPExcel style text to center

I'm using PHPExcel with codeigniter to generate .xlx, .xlxs file, Every thing is working perfect except text formatting. Here is the screenshot of html view that I'm passing to PHPExcel library to generate .xlx file.
And Here is the output.
As you can see that text indentation and styles are removed. Here is my code used to generate output.
public function html_to_excel_download($filename, $data=null){
if ($data != null) {
// proper encoding of data UTF-8 for unicode characters
$data = chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $data);
// Put the data into a temporary file
$tmpfile = time().'.html';
file_put_contents($tmpfile, $data);
// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML;
$content = $reader->load($tmpfile);
// Excel Writer
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
// Download File
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
unlink($tmpfile);
exit();
}
}
How can I indent title text to center?
you may try another way to do that...
Step 1) Define "$this->excel->setActiveSheetIndex(0);" at the top of function
step 2) Define style array and add it as a variable with excel object like,
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => '2F4F4F')
),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
Step 3) $this->excel->getActiveSheet()->getStyle('A3:Z3')->applyFromArray($styleArray);
Note: You have to use getStyle() in your code to apply specific styles on column/row
// single column A, setting e.g. horizontal alignment
$objWorksheet->getStyle('A')->getAlignment()->setHorizontal(...);
// range of columns A to K
$objWorksheet->getStyle('A:K')->getAlignment()->setHorizontal(...);
AND you can see full documentation on this site for formatting SHEET
HERE
There are two ways you can get rid of this issue, one is without json array:
$doc->getActiveSheet()->getStyle('A1:H1')->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
where $doc = new PHPExcel(); or a PHPExcel object
The second is using the json array as described here
I'm pretty confident that you'll find all instructions about this library in the official documentation

Drupal 8 images with image style

In drupal 7, i use function image_style_url('style', uri) to generate new image with style and return image's path. so what will be instead of it in drupal 8? thanks
Per the change records:
use Drupal\image\Entity\ImageStyle;
$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);
You should try to use the new Drupal functions wherever possible.
Instead, use:
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
$fid = 123;
$file = File::load($fid);
$image_uri = ImageStyle::load('your_style-name')->buildUrl($file->getFileUri());
Edited as per https://www.drupal.org/node/2050669:
$original_image = 'public://images/image.jpg';
// Load the image style configuration entity
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('thumbnail');
$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);
In your Controllers and other OOP part of Drupal you can use :
use Drupal\image\Entity\ImageStyle;
$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);
And in YOUR_THEME.theme file while Error: Class 'ImageStyle' not found in YOURTHEMENAME_preprocess_node you can do it with the follwing
$path = 'public://images/image.jpg';
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl($path);
Another method is provide a renderable array and let the drupal Render engine render it.
$render = [
'#theme' => 'image_style',
'#style_name' => 'thumbnail',
'#uri' => $path,
// optional parameters
];
I have found that I often want to preprocess the image to apply an image style to an image on a node or a paragraph type. In many cases I have created a paragraph that allows the user to choose the width of the image as a percentage. In the preprocess I would check the value of the width and apply the correct image style.
use Drupal\image\Entity\ImageStyle;
function THEME_preprocess_paragraph__basic_content(&$vars) {
//get the paragraph
$paragraph = $vars['paragraph'];
//get the image
$images = $paragraph->get('field_para_image');
//get the images value, in my case I only have one required image, but if you have unlimited image, you could loop thru $images
$uri = $images[0]->entity->uri->value;
//This is my field that determines the width the user wants for the image and is used to determine the image style
$preset = $paragraph->get('field_column_width')->value;
$properties = array();
$properties['title'] = $images[0]->getValue()['title'];
$properties['alt'] = $images[0]->getValue()['alt'];
//this is where the Image style is applied
switch($preset) {
case 'image-20':
$properties['uri'] = ImageStyle::load('width_20_percent')->buildUrl($uri);
break;
case 'image-45':
$properties['uri'] = ImageStyle::load('width_45_percent')->buildUrl($uri);
break;
case 'image-55':
$properties['uri'] = ImageStyle::load('width_55_percent')->buildUrl($uri);
break;
case 'image-100':
$properties['uri'] = ImageStyle::load('width_100_percent')->buildUrl($uri);
break;
}
//assign to a variable that the twig template can use
$vars['basic_image_display'] = $properties;
}
In this example, I am preprocessing a specific paragraph type named "basic_content" but you can do the same thing with a node preprocess. Continuing my example, I would have a twig template named paragraph--basic_content.html.twig to handle the display of that paragraph type.
Displaying the image would be something like this in the twig file.
<img class="img-responsive" src="{{basic_image_display['uri']}}" alt="{{ basic_image_display['alt'] }}" title="{{ basic_image_display['title'] }}"/>
$view_mode = $variables['content']['field_media_image']['0']['#view_mode'];
$display_content = \Drupal::service('entity_display.repository')
->getViewDisplay('media', 'image', $view_mode)->build($media_entity);
$style = ImageStyle::load($display_content['image'][0]['#image_style']); $original_image = $media_entity->get('image')->entity->getFileUri();
$destination = $style->buildUri($original_image);
This is how you get image style from a media image entity.
Works for me from a classic Drupal database Query in .module file :
$query = \Drupal::database()->select('file_managed', 'f' );
$query->addField('f', 'uri');
$pictures = $query->execute()->fetchAll();
foreach ($pictures as $key => $picture) {
$largePictureUri = entity_load('image_style', 'large')->buildUrl($picture->uri);
}
I used in Drupal 8 this code. It's working fine.
$fid = 374; //get your file id, this value just for example
$fname = db_select('file_managed', 'f')->fields('f', array('filename'))->condition('f.fid', $fid)->execute()->fetchField();
$url = entity_load('image_style', 'YOUR_STYLE_NAME')->buildUrl($fname);

Resources