2

I use this function in my wordpress function.php

<?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 call in archive, search and other wp phps with this:

<img src="<?php echo catch_that_image() ?>" width="250">

Here is the problem, all I need is offtheme support, since I don't use WordPress for upload images and inserting into the post. I need that each image that appears will be automatically resized to width 250 and 141 height.
Currently they are just used as the big images and resized via width height entries. I need new function that will make custom sized jpg files and use them.

Check this Link and you will understand what I want. How can I do that?

Nirav Madariya
  • 1,292
  • 2
  • 18
  • 34
Techuser
  • 115
  • 1
  • 9

1 Answers1

1

You need to use either PHP's ImageMagick or GD functions to work with images.

With GD, for example, it's as simple as...

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

And you could call this function, like so...

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

Answer from here.

Nirav Madariya
  • 1,292
  • 2
  • 18
  • 34