百科狗-知识改变命运!
--

imagecreatefromjpeg() - gd函数(图像处理)

乐乐12个月前 (11-21)阅读数 14#技术干货
文章标签文件名

imagecreatefromjpeg()

(PHP 4, PHP 5, PHP 7)

由文件或 URL 创建一个新图象。

说明

imagecreatefromjpeg(string $filename): resource

imagecreatefromjpeg()返回一图像标识符,代表了从给定的文件名取得的图像。

Tip

如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见fopen()。各种wapper 的不同功能请参见支持的协议和封装协议,注意其用法及其可提供的预定义变量。

参数

$filename

JPEG 图像的路径。

返回值

imagecreatefromjpeg() - gd函数(图像处理)

成功后返回图象资源,失败后返回FALSE

范例

处理创建过程中的错误

以上例程的输出类似于:

注释

Note:JPEG 支持仅在 PHP 与 GD-1.8 或更高版本一起编译时可用。

Warning

Windows 版本的 PHP 在 4.3.0版之前不支持通过此函数访问远程文件,即使已经启用allow_url_fopen.

This function does not honour EXIF orientation data. Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg(). Below is a function to create an image from JPEG while honouring EXIF orientation data. 
This little function allows you to create an image based on the popular image types without worrying about what it is: 
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!
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system. I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section. Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser. So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images. I have been testing for several days with hundreds of various size images and it seems to work well. Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking. Best of luck.
--- from move_upload_file post ---
I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails. My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails. This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload. The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.
The secret sauce is:
1. adjust server memory size, file upload size, and post size
2. convert image to standard formate (in this case jpg) and scale
The server may be adjusted with the .htaccess file or inline code. This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.
htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M 
In addition to yaroukh at gmail dot com comment.
It seems that even a small image can eat up your default memory limit real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you can change it dynamically using ini_set. Therefore, we can "allocate memory dynamically", to prevent those memory limit exceeded errors. 
###--- imagecreatefromjpeg only opens JPEG files from your disk.
###--- To load JPEG images from a URL, use the function below.
function LoadJPEG ($imgURL) {
  ##-- Get Image file from Port 80 --##
  $fp = fopen($imgURL, "r");
  $imageFile = fread ($fp, 3000000);
  fclose($fp);
  ##-- Create a temporary file on disk --##
  $tmpfname = tempnam ("/temp", "IMG");
  ##-- Put image data into the temp file --##
  $fp = fopen($tmpfname, "w");
  fwrite($fp, $imageFile);
  fclose($fp);
  ##-- Load Image from Disk with GD library --##
  $im = imagecreatefromjpeg ($tmpfname);
  ##-- Delete Temporary File --##
  unlink($tmpfname);
  ##-- Check for errors --##
  if (!$im) {
    print "Could not create JPEG image $imgURL";
  }
  return $im;
}
$imageData = LoadJPEG("http://www.example.com/example.jpg");
Header( "Content-Type: image/jpeg");
imagejpeg($imageData, '', 100);
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.
There is my actual script to resize image without distortion to generate a thumbnail and/or show a smaller to browser. 
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. 
Estimated memory needed for ImageCreateFromJPEG
First I supposed simple width*height*bpp will be enough, it isn't though; there is some pretty big overhead.
$imageInfo = GetImageSize($imageFilename);
$memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
With memory_limit enabled running out of memory causes script to crash; above written will tel you how much memory you're gonna need for creating an image-resource out of image-file. So in conjunction with Memory_Get_Usage() and Get_CFG_Var('memory_limit') you can avoid the mentioned ending. (Yet there won't be too many images blocked from processing that would still fit in the memory, as the results of this are pretty accurate.)
I am using PHP 4.3.8 and GD 2.0.23-compatible, and this function does not return an empty string on failure as stated. This line:

outputs:
bool(false)
Of course this doesn't matter unless you're using a strict comparison operator to evaluate the result, but I thought I'd point it out.
I have to say recompiling PHP from the sources and enabling JPEG support in gd took me awhile to figure out.
Somewhere especially configure --help should have stated that --with-jpeg-dir is MANDATORY if you want to have JPEG support. And even if you did so, it doesn't mean you'll get it. If it's wrongly configured, no error is going to be output, all you get is "no JPEG support". What's more confusing is when JPEG support is disabled phpinfo won't say "JPEG Support: disabled", but just omit the entry so you won't even realize something is wrong.
If you recompile PHP or gd, make sure:
- rm -f config.cache FIRST
- make clean (this helps A LOT), actually you can just delete modules/gd.*, and every *.o in ext/gd. this part actually gave me the best headache
- ./configure --with-jpeg-dir=/usr/lib OR any other directory which contains the BINARY library of libjpeg
- make, make install
phpinfo should now display jpeg support... good luck.
(you lucky guys who already have PHP 5 installed on your server... you don't have to go through all the mess I had)
I encountered a very strange behaviour:
The background: 
Each time users uploaded images, the original file was stored along with a thumbnail and a medium sized version for small-sized slideshows.
that means that on upload all of these original images were acknowledged by php as valid jpg
The change:
I created a new slideshow script that featured full-screen display. My old "medium-sized" version were only about 600px wide which caused them to luck all ugly after stretching that to modern screen sizes.
--> I created a small script that opens all original images and saves bigger "medium-sized" versions than the once I had.
the problem:
for some reason about 1/3 of all images (not the last third but always the same images) were now labeled as "... is not a valid JPEG file ..." by php
the cause:
still unknown
the solution:

Each time the local approach fails the script falls back to loading the same file "from the outside" via the below mentioned "LoadJPEG" script - big thanks to the author!
That worked even though I'm talking about the exact same file on the exact same server. The only difference is that one time it's accessed locally and the second via port 80.
when using this, watch for correct paths relative to your script and the possibly different path relative to your domain.
If you have a blank in the file name, and you use a local URL, this function works. Not so with a fully qualified URL 
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.)
regarding e dot a dot schultz at gmail dot com post
i tried the script (with the bugfixes posted later) and still got memorytrouble. most often it is still not enough memory to upload big images, even if it seems to calculate right. so this helped my perfectly:
$newLimit = $newLimit+3000000; (before passing it to the ini_set() function).
extremly simple and maybe not the best solution, but it works for now (you sure can give it less than an additional 3mb, just try what works for you).
It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path
The prior script by "e dot a dot schultz at gmail dot com", have a bug
$memoryLimitMB don't have a value
Add 
     $memoryLimitMB = 8;
Before
     $memoryLimit = 8 * $MB;
And change that line for:
     $memoryLimit = $memoryLimitMB * $MB;
--------------
Something similar happens with the script by "JohnBrook at pobox dot com"
$memoryLimit don't have a value
Change:
$memoryLimit = $memoryLimit * $MB;
For:
 $memoryLimit = $memoryLimitMB * $MB;
Matt reported that PHP crashs using imagecreatefromjpeg() - that's true and it took me a lot of time to find the error - but not only the Canon PowerShot S70, also the Canon PowerShot A400 lets PHP (5.1.2) crash, without any chance to catch it!
So I exclude all Canon PowerShot images with the following check:
  function check_canonpowershot($filename) 
  {
    if (strpos(file_get_contents($filename), 'Canon PowerShot') !== false) 
    {
      return true;
    }
    return false;
  }
Also, here is the same formula presented in a somewhat more human-readable way, if you'd rather: 
Additional note on allocating memory: The 1.65 in the formula provided below by yaroukh and Karolis is evidently a "fudge factor" arrived at through experimentation. I found that I had to nudge it up a little bit in order to accurately predict the memory that would be needed, otherwise the allocation still failed. In my case, I went right to 1.8 and that has worked so far. Your mileage may vary, so experiment as needed.
The ImageCreateFromJPEG() function is capable of throwing an emalloc() error. If this happens, the script will die, but the error will be in your error logs. You should ensure that you have memory available before creating a large image from a jpeg file.
To all those having trouble with a message to the effect of:
CreateImageFromJpeg() not supported in this PHP build
Start by adding --with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)
Hello Karolis
My solution was intended to solve situations when your webhoster puts a limit on the memory usage; in such a situations ini_set doesn't work ofcourse (even for variables that have 'PHP_INI_ALL' flag in a typical PHP-installation).
Have a nice day
 Yaroukh
I was experiencing troubles with imagecreatefromjpeg() as it outputted errors even when called with @ in front. ini_set("gd.jpeg_ignore_warning", 1) didnt work for me, so I came up with another simple solution. 
The problem is caused by gd error output, so by redirecting STDERR to /dev/null all the error messages in it are supressed and you can still use regular STDOUT for your error output.
So, just use 
I just wanted to note here something i found else where that was very helpful to me when using jpeg images. when using imagecreatefromjpeg() it can be difficult to allocate new colors. 
The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.
I encountered a problem with this function on a windows system. Instead of returning false in case of the file not being a JPG, the function resulted in an error: 
"imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error".
To get around this first check whether the file is a JPEG file using its mime type, if it is not return false.
Had to fight with this error message:
imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error
and found, that some picture tools like GIMP are adding EXIF-Informantions about changes.
Those pictures are running in the above problem.
Using an easy picture tool like Windows Paint - save the image new - and imagecreatefromjpeg worked for me.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)