Display blob image in symfony 2 - image

I need to display images stored in my database, from users in my symfony 2 application.
I've searched and I found examples such as:
Php Display Image Blob from Mysql
The line:
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
It didn't worked for me.
How to return an image file and display it in user's profile or a gallery page?

I created this action that searches the blob data in my table: Empleado.
/**
* #Route("/employee/photo/{id}", name="zk_time_employee_photo", requirements={"id" = "\d+"}, defaults={"id" = 1})
*/
public function photoAction()
{
$request = $this->getRequest();
$workerId = $request->get('id');
if (empty($workerId))
//throw exception
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('ZkTimeBundle:Empleado');
$photo = $repository->findPhoto($workerId);
if (empty($photo))
//throw exception
$response = new StreamedResponse(function () use ($photo) {
echo stream_get_contents($photo);
});
$response->headers->set('Content-Type', 'image/png');
return $response;
}
This part is essential (works for both formats, no matters the original format stored):
$response->headers->set('Content-Type', 'image/png');<br>
OR
$response->headers->set('Content-Type', 'image/jpeg');<br>
In order to display it I chose:
<img src="{{ asset(path('zk_time_employee_photo', {'id': employee.Id})) }}"/>
The base is the same for multiple images (carousel) or a gallery.
I hope this helps, because the web has empty results about it or not focused in Symfony2. Mainly, pure PHP.
This guys were very helpful:
Answer #1: symfony2-how-to-display-download-a-blob-field
Answer #2: symfony2-path-to-image-in-twig-template

Related

Tracking clicks on Download button and save in database

I have simple Download button which is looks like this
<a download="{{ $thumb }}" href="{{ $thumb }}" class="btn btn-success">Download Image</a>
It is appearing on page when the image is found. The button is working perfectly and is downloading the image.
The page has simple input field which user can search the image and if image is found it's showed on page with button download.
I've made a function which saves each string which is searched and now I'm wondering if I can save also if button Download is clicked e.g. the image is downloaded.
Can someone show me an example? I'm using laravel 5.4 here. So maybe I need to pass to the controller click event?
Current controller function
public function getImage(Request $request)
{
$url = get_curl_content_tx('http://example.com/api?url='.$request->input('url'));
$items = json_decode($url, true);
$thumb = $items['thumbnail_url'];
$db_save = new Image();
$ip = $request->ip();
$ip = DB::connection()->getPdo()->quote($ip);
$db_save->url = $request->input('url');
$db_save->ip = DB::raw("inet_aton($ip)");
$db_save->save();
return view('getImage',compact('thumb'));
}
Yes. Make sure that the href is going to a route where you keep track of these records and you can pass on the specific image to update the Record Model of the Image model itself if the counter is there? Something like this:
public function TrackDownload(Image $image){
$imageRecord = Record::where('image_id', '=', $image->id);
$imageRecord->update([
'download_counter' => $imageRecord->download_counter + 1;
]);
return redirect()->route();
}

PHP Sessions: Generate a variable and save it for session

I am totally new to php sessions. I am not able to get a simple task done.
This is what I am trying to do:
A visitor of my website gets shown a random image
well this part works so far. But everytime the user goes on to another page (I have this random image shown on all pages) the script generates a new random image to be shown.
What I want to do now is:
Save the random image variable to a session so he will see the same image on each page he visits while he has the session saved.
Here is my working code to get a random image without saving it into sessions. If anybody could help me with how the code should look like so it works with sessions would be awesome. Remember: I am a total newby when it comes to sessions.
As you can see I need the variable $img to be stored into a session after it got generated. And the script only to strt again on a new site visit if a user hasnt stored the $img variable in his session.
<?php
function getImagesFromDir($path) {
$images = array();
if ( $img_dir = #opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
// checks for gif, jpg, png
if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num = array_rand($ar);
return $ar[$num];
}
$root = '';
// use if specifying path from root
//$root = $_SERVER['DOCUMENT_ROOT'];
$path = 'images/';
// Obtain list of images from directory
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
?>
<img src="/<?php echo $path . $img ?>" alt="image" />
You'll need to add this at the top of every page to get your image:
session_start();
if(isset($_SESSION['UserImg'])){
$img = $_SESSION['UserImg'];
}
else {
$img = getRandomFromArray($imgList);
$_SESSION['UserImg'] = $img;
}
This should work out!
on top of each page call:
session_start();
To safe variable in session for example:
$_SESSION['imageid'] = $ID
To get the variable back:
$imageid = $_SESSION['imageid']

How to render banners alongside featured items in home page

I'm making a custom template form joomla 2.5, and one of the goals for the development is to include a banner after each featured article iteration.
After a long research I can render a banner into /template_name/html/com_content/featured/default_item.php with the following code:
$document = JFactory::getDocument();
$renderer = $document->loadRenderer('modules');
$position = "nota";
$options = array('style' => 'raw');
echo $renderer->render($position, $options, null);
But the issue is that each iteration resets the banner list so I have the same banner repeated with each featured article.
I tried to include the banner module using the same code in /template_name/html/com_content/featured/default.php without success. Lately I'd try with <jdoc:include type="modules" name="nota" style="raw" /> and it didn't works too, so I will appreciate any help to solve this point.
Thanks in advance.
You can solve this in two ways.
The right way
Copy and rename the banner module (fx. to mybanners), change the getList() method in the helper file to retrieve different banners on each call. This could fx. be:
class modMybannersHelper
{
static function &getList(&$params)
{
static $index = 0;
JModelLegacy::addIncludePath(JPATH_ROOT.'/components/com_banners/models', 'BannersModel');
$document = JFactory::getDocument();
$app = JFactory::getApplication();
$keywords = explode(',', $document->getMetaData('keywords'));
$model = JModelLegacy::getInstance('Banners', 'BannersModel', array('ignore_request'=>true));
$model->setState('filter.client_id', (int) $params->get('cid'));
$model->setState('filter.category_id', $params->get('catid', array()));
$model->setState('list.limit', 1);
$model->setState('list.start', $index++);
$model->setState('filter.ordering', $params->get('ordering'));
$model->setState('filter.tag_search', $params->get('tag_search'));
$model->setState('filter.keywords', $keywords);
$model->setState('filter.language', $app->getLanguageFilter());
$banners = $model->getItems();
$model->impress();
return $banners;
}
}
This is just a sketch; you still need to handle the case of $index being greater than the number of records.
The hacky way
The retrieval code has only one port open to inject conditions - the documents's keywords.
So you could (in your template file) store the original keywords an replace them with a keyword to identify a banner. The banner must have the same keyword in that case.
$document = JFactory::getDocument();
$keywords = $document->getMetaData('keywords');
$renderer = $document->loadRenderer('modules');
$position = "nota";
$options = array('style' => 'raw');
$document->setMetaData('keywords', 'banner_key');
echo $renderer->render($position, $options, null);
$document->setMetaData('keywords', $keywords);
Either way, caching may prevent that from work, so you might have to turn it off (I didn't check that).

WordPress: snag first image from a gallery

On my homepage, I'm trying to output the first image of each post, and I'm able to successfully do that using this code in my functions.php:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
and then I call it in my loop like this:
<img src=”<?php catch_that_image(); ?>” />
The problem with this method is that it won't work if I place a gallery in that same post. I'm confused because the output of the post still renders the img markup, and my assumption is that catch_that_image() should snag that markup? Is my thinking incorrect? Is there a better way to handle this?
The gallery is placed inside your post using a WordPress short-tag. The shorttag is transformed into HTML-image tags when the filter for transforming the shorttag is applied.
The following might work, but I am not sure:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$transformed_content = apply_filters('the_content',$post->post_content);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $transformed_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Please let me know if this was useful or if it was pointing you into the right direction!
Codex Links:
http://codex.wordpress.org/Gallery_Shortcode
http://codex.wordpress.org/Function_Reference/apply_filters
http://codex.wordpress.org/Function_Reference/do_shortcode

WordPress plugin: finding the <!--more--> in the_content

I'm writing a WordPress plugin that filters the_content, and I'd like to make use of the <!--more--> tag, but it appears that it has been stripped out by the time it reaches me. This appears to be not a filter, but a function of the way WordPress works.
I could of course resort to reloading the already-loaded content from the database, but that sounds like it might cause other troubles. Is there any good way for me to get the raw content without the <!--more--> removed?
Chances are, by the time your plugin runs, <!--more--> has been converted to <span id="more-1"></span>
This is what I use in my plugin, which injects some markup immediately after the <!--more--> tag:
add_filter('the_content', 'inject_content_filter', 999);
function inject_content_filter($content) {
$myMarkup = "my markup here<br>";
$content = preg_replace('/<span id\=\"(more\-\d+)"><\/span>/', '<span id="\1"></span>'."\n\n". $myMarkup ."\n\n", $content);
return $content;
}
You can use the follow code:
The !is_single() will avoid display the more link in the View Post page.
add_filter('the_content', 'filter_post_content');
function filter_post_content($content,$post_id='') {
if ($post_id=='') {
global $post;
$post_id = $post->ID;
}
// Check for the "more" tags
$more_pos = strpos($filtered_content, '<!--more-->');
if ($more_pos && !is_single()) {
$filtered_content = substr($filtered_content, 0, $more_pos);
$replace_by = '<a href="' . get_permalink($post_id) . '#more-' . $post_id
. '" class="more-link">Read More <span class="meta-nav">→</span></a>';
$filtered_content = $filtered_content . $replace_by;
}
return $filtered_content;
}
Based on Frank Farmer's answer I solved to add thumbnail photo after the generated more tag (<span id="more-...) in single.php file with this:
// change more tag to post's thumbnail in single.php
add_filter('the_content', function($content)
{
if(has_post_thumbnail())
{
$post_thumbnail = get_the_post_thumbnail(get_the_ID(), 'thumbnail', array('class'=>'img img-responsive img-thumbnail', 'style'=>'margin-top:5px;'));
$content = preg_replace('/<span id\=\"(more\-\d+)"><\/span>/', '<span id="\1"></span>'.$post_thumbnail, $content);
}
return $content;
}, 999);

Resources