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
Related
Im working on a template for a website that has already more than 50,000 articles and images assigned to every article.
Before now the article image was visible only inside every article, but now I would like to use thumbnails.
I don't have access to modify the upload image form, so the solution should be something like virtual thumbs created from the original images...
What will be the best approach in this case?
Using Mr. Thumb like I advised a simple script to get it working would be
<?php
include './mrthumb.class.php';
// The image you are resizing. Can be a local path as well.
$image = $_GET['i'];
$quality = 100; // percent
// In this example we are resizing the image in proportionate sizes.
// Below we are specifying the MAX width and height.
$width = 100; // Pixels
$height = 130; // Pixels
// Start Mr. Thumb v1.0
$mrthumb = new MrThumb();
// Render the image
$mrthumb->render( $image );
// Resize the image proportionately
// $mrthumb->constrain( $width, $height );
$mrthumb->proportion( $width, $height );
// Finally, output the image to the browser!
// Optionally we can save the image to a destination
// $mrthumb->saveto( $destination, $filename, $quality );
$mrthumb->output( $quality );
// Clean up after you are done! ;)
$mrthumb->clear_cache();
?>
Then save that to your web server along with the mrthumb class and call a thumbnail in your webpage like
<img src="./mrthumb.php?i=images/myimage.jpg" alt="My Image" />
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.
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);
}
}
?>
I need to show multiple posts on my website. These posts are combined of internal and external posts. The external posts are periodically imported and saved in my DB using a cronjob.
Before showing the posts I extract the text from all HTML. In addition I try to locate the first image contained in the post, continuing until I find an image which height & width meets my requirements. (I only show a small version of the text, and one picture from the post as a teaser)
For the purpose of finding the most suitable picture, I use getimagesize, but unfortunately this often creates PHP Execution time of several seconds!
How can I speed up my function below? I'm desperate for tips and good tweaking methods!!
Thanks in advance
//extract text without tags from blog post
$content = str_get_html("".$post_text."")->plaintext;
$max_width = 475;
$picture_id = 0;
//fetch images from blog post
foreach($html->find('img') as $e) {
//get picture attributes
list($width, $height, $type, $attr) = getimagesize((is_absolute_url($e->src) ? $e->src : $_SERVER['DOCUMENT_ROOT'].$e->src));
//adjust image width & height, so it's the size of the page
$new_width = $max_width;
$new_height = $new_width / $width * $height;
//find percentage of current width versus max width
$percentage = ($width / $max_width) * 100;
//select picture for display and resizing if the picture is large enough (we don't want to stretch it too much)
if($percentage >= 60) {
$e->width = $new_width;
$e->height = $new_height;
$picture = array('src' => $e->src, 'width' => $e->width, 'height' => $e->height);
//stop after first picture is found :: we only need one per post
if (++$picture_id == 1) break;
}
}
Reason: It is a very well known issue that getimagesize works slow on remote files.
Solution: It is advised to store the files on your local server (temporarily) and then do getimagesize on it.
When you pass a url as a parameter to getimagesize, it gets the image through HTTP, what is a slow process.
You should get its size only the first time and save it in a database for the future.
I have a 1 pixel tall by 760 pixel wide image that I use as a repeating vertical background image. The right side of this image is filled with a spot color (the remaining left side of the image is white).
The purpose of this background image, in my css based layout, is that it provides the illusion that the sidebar background color runs all the way down the page (easy to do with tables, but no so much with CSS positioning).
What I need to do is to figure a way to feed a php script (background-image.php) which contains the imagecreatefromgif function, a hex number and have it use that to repaint the spot color of the image to match the spot color that's passed in and save the resulting image onto the server, overwriting the default one.
Ideally, I'd not like to have to call this function everytime the template loads, and onlydo it when the user elects to change the template colors. So once they do that, I'd just like to modify the existing image I've got on the server which will always be called "sidebar_bg.gif"
Any ideas on how to do this are much appreciated.
Something like this could do it:
$token = md5(serialize(array($red, $green, $blue)));
if (!file_exists('cachedir/'.$token.'.gif'))
{
$img = imagecreatefromgif('origfilename.gif');
$color = imagecolorallocate($img, $red, $green, $blue);
for ($i = $startPixel-1; $i < $endPixel; $i++)
{
imagesetpixel($img, $i, 0, $color);
}
imagegif($img, 'cachedir/'.$token.'.gif');
}
serveFile($token);
EDIT: Added caching to example code
Just an addition to this post. You can convert HEX color into RGB notation with the folowing function:
function hexToRGB ($hexColor)
{
$output = array();
$output['red'] = hexdec($hexColor[0].$hexColor[1]);
$output['green'] = hexdec($hexColor[2].$hexColor[3]);
$output['blue'] = hexdec($hexColor[4].$hexColor[5]);
return $output;
}
e.g. try:
var_dump(hexToRGB("FFFFFF"));