Wordpress - custom image sizes not working - php

I am having trouble with using custom image size.
I have this in function.php:
//function to call first uploaded image in functions file
function main_image() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment
&post_mime_type=image&order=desc');
if($files) :
$keys = array_reverse(array_keys($files));
$j=0;
$num = $keys[$j];
$image=wp_get_attachment_image($num, 'test', true);
$imagepieces = explode('"', $image);
$imagepath = $imagepieces[1];
$main=wp_get_attachment_url($num);
$template=get_template_directory();
$the_title=get_the_title();
print "<img src='$main' alt='$the_title' />";
endif;
}
add_image_size('test', 145, 145, true);
So what this does it check for the post's thumbnail, and if there is none, it searches to the first image in a post. So far so good, but I can't get it to display the image size that I want.
wp_get_attachment_image($num, 'test', true); should be displaying the 'test' size, which is created when uploaded (I also ran regenerate thumbnails, and all the images have been resized). But no matter what I enter instead of test (full, medium, thumbnail, etc), the code always call the full image (which gets squished to the 145x145 size instead of displaying the cropped thumbnail).
The code is from http://www.wpbeginner.com/wp-themes/how-to-set-a-default-fallback-image-for-wordpress-post-thumbnails/ (its old code, so probably some change in WP is making this fail).
Its the last thing I need to do to finish a site.

Related

Image manipulation not updated in cache

On a page where users can rotate their uploaded picture, there is a button to rotate the picture. This is done using Intervention image, but the same result (and problem) has been achieved using PHP.
The problem is that the image rotation works, but the rotated image is not shown in the browser. This is probably due to cache, because when manually emptying the cache, the rotated picture is indeed shown in the browser.
public function rotate($picture_id) {
// get picture location
$path = Picture::where('id',$picture_id)->first()->location;
// Rotate the picture
$path_orig = storage_path('app/public/'.$path);
$img_orig = Image::make($path_orig)
->rotate(-90)
->save($path_orig);
// Rotate thumbnails etc
...
return Redirect::back();
}
SOLUTION
Update the filename with a random string.
public function rotate($picture_id) {
// get picture location
$path = Picture::where('id',$picture_id)->first()->location;
// Path to picture
$path_orig = storage_path('app/public/'.$path);
$path_s = public_path($path);
// New path
do {
$newKey = str_random(40);
$ext = File::extension($path_orig);
$dir = dirname($path_orig);
$path_L_new = $dir.'/'.$newKey.'.'.$ext;
$path_S_new = public_path('folder/'.$newKey.'.'.$ext);
}
while ( count(Picture::where('location',$path_L_new)->get()) > 0 );
// Rotate images
$img_L_new = Image::make($path_orig)
->rotate(-90)
->save($path_L_new);
$img_S_new = Image::make($path_s)
->rotate(-90)
->save($path_S_new);
// Delete old files
Storage::delete($path);
File::delete(public_path($path));
// Update location
$pic = Picture::where('id',$picture_id)->first()->update(array('location' => 'folder/'.$newKey.'.'.$ext));
// Show new picture
return Redirect::back();
}
You have to append a random or unique string at the of the image src:
<img src="/path/to/file.jpg{{ time() }}">
But be careful that don't append new random string to the end of the image src when the image is not being updated. If you do, the image won't be cached.
Proper way:
When an image updated, it's better to store a random string for this image and store it in database. And when displaying the images, append peer random string to it. Don't generate new random string on every call.

one single image url for an avatar to display random image from a folder (server-side php script)

a long time ago i once did found a php script that contained only about 6 short lines of it if i remember correctly. Yet no luck, i couldn't find anything like that anymore, so i am gonna ask for help from you.
It was only one file "rotate.php" and a folder that contained all by myself chosen images, the script was supporting different dimensions and with different extensions (jpg, png, gif) as i remember.
Script generated one single url that could be used as an image url for an avatar or between [img] tags on forums with bbcode support.
Respectively, when someone visits my forums profile or sees my comment on forums, per every visit/refresh it always shows a random image as my avatar.
There seems to be many simple variations to create a random image slideshow for my own websites logo or something, but i can't figure a way to make it work for external sites like with previously mentioned single url.
Give me some hope, thanks.
Hope it helps, you can use PHP inbuilt function called opendir($path) to open the folder in path and read the directory.
<?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];
}
$path = 'imagesfolder/';
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
?>
IN HTML:
<img src="<?php echo $path . $img; ?>" alt="" />
Ref: http://www.dyn-web.com/code/basics/random_image/random_img_php.php

Work with dynamic Images in responsive web application

I am working on responsive web application. My designer used 370x700px Images in static pages. It works perfectly with responsive with the css and js code for images including this width:100% height:auto.
In this site I am uploading product images from the admin panel.In without responsive website I was creating different size of thumbnails, but In this case I am worried that should I create thumbnail of size 370x700px? These images are too big to load and i have to load 10 images on one page. minimum size of the image is 150kb. so 150*10 = 1500kb only for images except other contents. These are the small images, big images resolution is around 700x1800px which I will show on product detail page in zoom section.
Is there any other way to do it? should I create 370*700px thumbnail images from admin panel?
Here is some old code I wrote that will resize any image from a DB. It still uses the deprecated mysql_* but that is easy enough for you to update.
It is designed to take $GET arguments, img (the row on the db corresponding to the image), min,max,height,width. Depending on which of those are set, it will either fix an absolute value or try to fit the image to a size you need. This will allow you to upload one image only then resize that dynamically for your pages.
$sql=sprintf("SELECT image,filetype,width,height FROM image WHERE imageline='%s'",mysql_real_escape_string($_GET['img']));
$result=mysql_query($sql,$dbh);
$row=mysql_fetch_assoc($result);
$filetype=($row['filetype']!="")?$row['filetype']:"image/jpeg";
$content=base64_decode($row['image']);
$newheight=0;
$newwidth=0;
if($row['height']==0||$row['width']==0)
{
header("Content-type: $filetype");
echo ($content);
die;
}
if($_GET['max']>0)
{
if($row['height']>=$row['width'])
{
$_GET['height']=($_GET['max']>$row['height'])?$row['height']:$_GET['max'];
$_GET['width']=0;
}
if($row['width']>$row['height'])
{
$_GET['width']=($_GET['max']>$row['width'])?$row['width']:$_GET['max'];
$_GET['height']=0;
}
}
if($_GET['min']>0)
{
if($row['height']<=$row['width'])
{
$_GET['height']=$_GET['min'];
$_GET['width']=0;
}
if($row['width']<$row['height'])
{
$_GET['width']=$_GET['min'];
$_GET['height']=0;
}
}
if($_GET['height']>0&&$_GET['width']==0)
{
$newheight=$_GET['height'];
$newwidth=$row['width']*($_GET['height']/$row['height']);
}
if($_GET['height']>0&&$_GET['width']>0)
{
$newheight=$_GET['height'];
$newwidth=$_GET['width'];
}
if($_GET['width']>0&&$_GET['height']==0)
{
$newwidth=$_GET['width'];
$newheight=$row['height']*($_GET['width']/$row['width']);
}
if($newheight>0&&$newwidth>0)
{
$newheight=floor($newheight);
$newwidth=floor($newwidth);
$image=imagecreatefromstring($content);
$newimage=imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($newimage, $image, 0, 0, 0, 0, $newwidth, $newheight,$row['width'], $row['height']);
header("Content-type: image/jpeg");
imagejpeg($newimage);
die;
}
header("Content-type: $filetype");
echo ($content);
You can do a php script that can resize the images in the fly and use it something like this
/image-resizer.php?source=path-to-the-image-here&width=x&height=x

Code for displaying thumbnail images

I have a simple PHP script that enables users to upload images on a server. I am after some help in displaying these images as thumbnails in an HTMl page and then letting the user click on these thumbnails and then the original picture is displayed in a new page.
Can I use straight HTML for this? Or do I need some combination of javascript or PHP variant?
I know that there are many questions about this on stackoverflow, and I have tried them, but nothing is what I am after.
I would prefferably like the thumbnails be created on the 'fly' rather than me personally having to create each thumbnal when a user uploads an image.
So basically what language should I use to do this? And also can I have some source code if possible?
thanks
Creating thumbnails every time they are requested is a very bad idea - it takes a lot of processing power, which would be easily saved by keeping them around the first time you create them. I would suggest putting the thumbnail creation in the php script that processes the file upload, so that you save the image and its thumbnail to disk at the same time. You can also keep the thumbnail in memory, or wait until the first time it's requested to create it, but either way you cannot re-generate it every time it is requested.
It is possible to use html to change an image's size, by simply setting the width and/or height properties:
<img src='foo.jpg' alt='foo' width='500' height='300'/>
However, this is a bad idea if you aren't certain that the user will later want to view the full-sized image. The reason is that a thumbnail has a smaller filesize than the full image: if the client only wants to view the thumbnail, then you don't want to waste bandwidth (= your money and the client's time) sending them the full image.
As for your interface, you don't need javascript to accomplish that, just html. However, you will need a server-side script to create the thumbnails that your html page links to.
There are plenty of php thumbnail scripts out there.
Either you use a rewriter to still show the original path, but server a php thumbnail version. Or you have to have the url change to something like:
<img src="thumb.php?file=path/to/picture.jpg&size=128" />
Mighty Stuff
phpThumb
Are just such two. Best configured to utilize the cached folder. I use a modified version of the first script at work.
Here's a PHP script you can build appon only works with jpg images.
It will scan through a directory, normalize the image to a decent dimension and also make a thumb on the fly, then on next refresh it wont need to reprocess the image as its already present in the thumbs dir. Hope it helps...
Script placement
Root>
thisscript.php
/images/
someimage.jpg
someimage2.jpg
thisscript.php
<?php
// config section
$path = "./images/";
$thpath = $path."thumbs/";
// end configration
// Open the directory
$do = dir($path);
// now check if the thumb dir is available if not, create it!!
if (!is_dir($thpath)){
mkdir($thpath);
}
$output = '<div>';
while (($file = $do->read()) !== false){
if (is_dir($path.$file)){
continue;
}else{
$info = pathinfo($path.$file);
$fileext = $info['extension'];
if (strtolower($fileext) == 'jpg'){
if (!is_file($thpath.$file)){
//Normalize Super lrg Image to 750x550
thumb_it($path, $file, $path,750,550,99);
//Make Thumb 200x125
thumb_it($path, $file, $thpath,200,125,99);
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}else{
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}
}
}
}
$output .='</div>';
echo $output;
//Functions
function thumb_it($dirn, $file, $thumbdir,$rwidth,$rheight,$quality){
set_time_limit(0);
$filename = $dirn.$file;
$thfilename = $thumbdir.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $file);
// get the filename and the thumbernail directory
if (is_file($filename)){
// create the thumbernail from the original picture
$im = #ImageCreateFromJPEG($filename);
if($im==false){return false;}
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
if (($width < $rwidth) && ($height < $rheight)){
$n_height = $height;
$n_width = $width;
}else{
// saveing the aspect ratio
$aspect_x = $width / $rwidth;
$aspect_y = $height / $rheight;
if ($aspect_x > $aspect_y){
$n_width = $rwidth;
$n_height = $height / $aspect_x;
}else{
$n_height = $rheight;
$n_width = $width / $aspect_y;
}
}
$newimage = imagecreatetruecolor($n_width, $n_height);
// resizing the picture
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
// writing to file the thumbnail
if(file_exists($thfilename)){chmod($thfilename, 0777);}
Imagejpeg($newimage, $thfilename, $quality);
imagedestroy($newimage);
imagedestroy($im);
}
}
?>

display image thumbnail by reading path from table and retrieving the image from folder

I would be grateful if anybody could help me out with this.
I have a table which stores the filepath of a set of images, e.g col filepath stores values like: ./phpimages/image3.jpg. Note that my images are stored in folder 'phpimages'
Now i want to loop through all the rows in my table and display thumbnails of the images.
Here is my code:
/
*************************Display all records from images table***************/
//create an instance is Image
$objImage = new Image;
$result = $objImage -> listImage();
$num_rows = mysql_num_rows($result);
//echo $num_rows."records in database";
while($row = mysql_fetch_assoc($result)){
$imagepath="'".$row["filepath"]."'"; // note that if i put $imagepath= "dog.jpg", it displays the image just once!
//set mime type content
header('Content-Type: image/jpeg');
//create original image
$image = imagecreatefromjpeg($imagepath);
//get image dimension
$dim=getimagesize($imagepath);
//Set thumb dimension
$thumbw = 100;
$thumbh = 130;
//create empty image
$thumb_image=imagecreatetruecolor($thumbw, $thumbh);
//Resize original image and copy it to thumb image
imagecopyresampled($thumb_image, $image, 0, 0, 0, 0,
$thumbw, $thumbh, $dim[0], $dim[1]);
//display thumb image
imagejpeg($thumb_image);
}
?>
Please can anyone tell me where my error lies? Many thanks for any help provided
Why not just use <img src="">
You can output only one imagejpeg($thumb_image); using this method. If you want to display all thumbnails in a combined image, you should merge your images to one PHP/GD image, and then output that one.
If you would like to output thumbnail images, then I advise you to use the following tool:
http://phpthumb.sourceforge.net/
So when you iterate through your images, you should output an <img src="" /> for each thumbnail.

Categories