Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

imagecreatefromjpeg

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagecreatefromjpeg -- Create a new image from file or URL

Описание

resource imagecreatefromjpeg ( string filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

Пример 1. Example to handle an error during creation

<?php
function LoadJpeg($imgname)
{
   
$im = @imagecreatefromjpeg($imgname); /* Attempt to open */
   
if (!$im) { /* See if it failed */
       
$im  = imagecreatetruecolor(150, 30); /* Create a black image */
       
$bgc = imagecolorallocate($im, 255, 255, 255);
       
$tc  = imagecolorallocate($im, 0, 0, 0);
       
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
       
/* Output an errmsg */
       
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return
$im;
}
header("Content-Type: image/jpeg");
$img = LoadJpeg("bogus.image");
imagejpeg($img);
?>

Результатом выполнения данного примера будет что-то подобное:

Подсказка: Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция "fopen wrappers". Смотрите более подробную информацию об определении имени файла в описании функции fopen(), а также список поддерживаемых протоколов URL в Прил. M.

Список параметров

filename

Path to the JPEG image

Возвращаемые значения

Returns an image resource identifier on success, FALSE on errors.

Примечания

Замечание: JPEG support is only available if PHP was compiled against GD-1.8 or later.

Внимание

Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если опция allow_url_fopen включена.



imagecreatefrompng> <imagecreatefromgif
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
imagecreatefromjpeg
dmhouse at gmail dot com
08-Aug-2007 03:37
For a script that allows you to calculate the "fudge factor" discussed below by Karolis and Yaroukh, try the following. Grab a few images, preferably some large ones (the script should cope with images of up to 10 megapixels or so), some small ones, and some ones in between. Add their filenames to the $images array, then load the script in your browser.

<?php

header
('Content-Type: text/plain');

ini_set('memory_limit', '50M');

function
format_size($size) {
  if (
$size < 1024) {
    return
$size . ' bytes';
  }
  else {
   
$size = round($size / 1024, 2);
   
$suffix = 'KB';
    if (
$size >= 1024) {
     
$size = round($size / 1024, 2);
     
$suffix = 'MB';
    }
    return
$size . ' ' . $suffix;
  }
}

$start_mem = memory_get_usage();

echo <<<INTRO
The memory required to load an image using imagecreatefromjpeg() is a function
of the image's dimensions and the images's bit depth, multipled by an overhead.
It can calculated from this formula:
Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor
Where Bytes per pixel = Bit depth/8, or Bits per channel * Num channels / 8.
This script calculates the Overhead fudge factor by loading images of
various sizes.
INTRO;

echo
"\n\n";

echo
'Limit: ' . ini_get('memory_limit') . "\n";
echo
'Usage before: ' . format_size($start_mem) . "\n";

// Place the images to load in the following array:
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
$ffs = array();

echo
"\n";

foreach (
$images as $image) {
 
$info = getimagesize($image);
 
printf('Loading image %s, size %s * %s, bpp %s... ',
        
$image, $info[0], $info[1], $info['bits']);
 
$im = imagecreatefromjpeg($image);
 
$mem = memory_get_usage();
  echo
'done' . "\n";
  echo
'Memory usage: ' . format_size($mem) . "\n";
  echo
'Difference: ' . format_size($mem - $start_mem) . "\n";
 
$ff = (($mem - $start_mem) /
         (
$info[0] * $info[1] * ($info['bits'] / 8) * $info['channels']));
 
$ffs[] = $ff;
  echo
'Difference / (Width * Height * Bytes per pixel): ' . $ff . "\n";
 
imagedestroy($im);
 
$start_mem = memory_get_usage();
  echo
'Destroyed. Memory usage: ' . format_size($start_mem) . "\n";

  echo
"\n";
}

echo
'Mean fudge factor: ' . (array_sum($ffs) / count($ffs));

?>
jhon at stockton dot com dot com
04-Jun-2007 01:02
// a function for resize the images(png,jpg,gif) in a directory
//for the png you must have the zlib actived

//$diror origin directory
//$dirdest destination directory
//$val value of resize(1,2,3..)
//$qual quality(80 if you don't know)

function imgres($diror,$dirdest,$val,$qual){
$q=$qual;
//open the directory
if (is_dir($diror)) {
   if ($dh = opendir($diror)) {
      while (($file = readdir($dh)) !== false) {
        if($file == "." || $file == ".."){continue;}
                 $k=explode(".",$file);
            if(strpos($k[1],"jpg")===0 || strpos($k[1],"jpeg")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefromjpeg("$image");
            $x=imagesx($im);
            $y=imagesy($im);   
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagejpeg($thumbnail, $salva, $q);        
                    }
            elseif(strpos($k[1],"gif")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefromgif("$image");
            $x=imagesx($im);
            $y=imagesy($im);   
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagegif($thumbnail, $salva, $q);
                }
            elseif(strpos($k[1],"png")===0){
            $salva=$dirdest.$file;
                    $image=$diror.$file;
            $im =imagecreatefrompng("$image");
            $x=imagesx($im);
            $y=imagesy($im);   
            $thumbnail=imagecreatetruecolor($x/$val,$y/$val);
            $im_ridimensionata=imagecopyresized( $thumbnail, $im, 0, 0, 0, 0, $x/$val,
            $y/$val, $x, $y);
            imagepng($thumbnail, $salva, $q);
                }
            else{
                echo "File not compatible(no jpg,gif or png)";
            }   
            }
            closedir($dh);
            }
    }
}
huguowen at cn dot ibm dot com
16-May-2007 11:57
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

Problem I meet:

When i run following function, which terminates at  

$img = @imagecreatefromjpeg($image_path);

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

Solution:

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini 
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it's not enabled by default.
You have to turn it on,
You may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension.

Change:
,extension=php_gd2.dll

To:
extension=php_gd2.dll

You may also have to correct the extension directory setting
from:
extension_dir = "./"
extension_dir = "./extensions"
To (FOR WINDOWS):
extension_dir = "c:/php/extensions"(php 4)
extension_dir = "c:/php/ext"(php 5)

Cheers!
sales at wholehogsoftware dot com
02-May-2007 09:10
I've found a bug in CentOS 4.x that, while previously addressed, does not seem to be directly addressed here as far as the nature of the bug is concerned.

If you are having a problem getting this function to work on CentOS 4.4 (may appear earlier) and are receiving this error:

Call to undefined function imagecreatefromjpeg()

This is because the installation *does* support JPG by default if you have libjpeg installed. However, the config script finds libjpeg in /usr/lib but it is never successfully added to the PHP build.

To fix this, you should recompile PHP and be absolutely sure to add '--with-jpeg-dir' to the config command. This should appear BEFORE the --with-gd option. Example:

'--with-jpeg-dir' '--with-gd'

If you don't put it before --with-gd, the option is completely ignored.

As always, be sure to do a 'make clean' before a 'make install'. I made the mistake of forgetting to check and wasted 30 minutes trying to resolve this problem simply because I forgot to clean up after myself previously.
henk_vd_bosch at planet dot nl
26-Jan-2007 04:41
When i run following function dis function terminates at the 
13th line where is says:
$img = @imagecreatefromjpeg($image_path);

no other code of the script gets executed. can anyone help me. i use PHP5 with GD lib support

function convertLQ($image_path)
{
  ClearStatCache();
  $file = basename($image_path);
  $dirname = dirname ($image_path);
  // set save path + name
  $save_path = $dirname.'/LQ/'.$file;
  // Load image
  $img = null;
  $ext = strtolower(end(explode('.', $image_path)));
  $image_path = htmlentities($image_path);
  if ($ext == 'jpg' || $ext == 'jpeg')
  {
    $img = @imagecreatefromjpeg($image_path);
  }
  else if ($ext == 'png')
  {
    $img = @imagecreatefrompng($image_path);
  }
  else if ($ext == 'gif')
  {
    $img = @imagecreatefromgif($image_path);
  }
  // If an image was successfully loaded, test the image for size
  if ($img)
  {
    // Get image size and scale ratio
    $width = imagesx($img);
    $height = imagesy($img);
    $scale = maxHeightLQ/$height;
    // If the image is larger than the max shrink it
    if ($scale < 1)
    {
      $new_width = floor($scale*$width);
      $new_height = floor($scale*$height);
      // Create a new temporary image
      $tmp_img = imagecreatetruecolor($new_width, $new_height);
      // Copy and resize old image into new image
      imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
      imagedestroy($img);
      $img = $tmp_img;
    }
  }
  // Create error image if necessary
  if (!$img)
  {
    $img = imagecreate(witdhErrorImage,heightErrorImage);
    $backgroundcolor = imagecolorallocate($img,70,70,70);
    $c = imagecolorallocate($img,70,70,70);
    $red = ImageColorAllocate($img,255,0,0);
    imageline($img,0,0,witdhErrorImage,heightErrorImage,$red);
    imageline($img,witdhErrorImage,0,0,heightErrorImage,$red);
    imagejpeg($img,$save_path,85);
    imagedestroy($img);
    return false;
  }
  // Save the image
  if ($ext == 'jpg' || $ext == 'jpeg')
  {
    imagejpeg($img,$save_path,85);
  }
  else if ($ext == 'png')
  {
    imagePng($img,$save_path);
  }
   else if ($ext == 'gif')
  {
    ImageGif($img,$save_path);
  }
  else
  {
    imagejpeg($img,$save_path,85);
  }
  imagedestroy($img);
  return true;
}
hvozda at ack dot org
30-Oct-2006 03:42
If imagecreatefromjpeg() fails with "PHP Fatal error:  Call to undefined function:  imagecreatefromjpeg()", it does NOT necessarily mean that you don't have GD installed.

If phpinfo() shows GD, but not JPEG support, then that's the problem.  You would think that --with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn't in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified...
info at daleconsulting dot com dot au
29-Aug-2006 06:34
In a post by Angel Leon, an example script was given that forms a thumbnail gallery using imagecreatefromjpeg.  I am fairly new to php scripts, but I found that the script did not display the table of thumbnail images if the row wasn't "filled" with images.. i.e. if there were 5 images in the folder and the script specified 3 rows in the table, then the page would only display the thumbnails for the first row and only three images were shown.  I found that if you specified the variable row with this equation, then the table would display properly:

$row = intval(count($files)+($row_size-1));

(This is the first line in the createThumbTable function.)
kapishonas at yahoo dot com
11-Jul-2006 04:56
script for nokia photos which end with FF D9 and still imagecreatefromjpeg() returns error.

<?php

error_reporting
( 32 );
header( 'Content-Type: image/jpeg' );

$imgPath = 'att.jpg';

// Atdod atpaka
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571