You are not logged in.

  • Login

Friday, February 18th 2011, 4:32pm

Tags

bilder, image resizing, on the fly, Resizing, thumbnail

Abstract

Hier erfahrt ihr wie ihr Vorschaubilder in PHP erstellt, speichert oder "on the fly" anzeigt.

Article

1. Thumbnail Klasse


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
 
/**
 * Generates a thumbnail of given source file image.
 * 
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 */
class Thumbnail {
	/**
	 * path to source file
	 *
	 * @var string
	 */
	protected $sourceFile = '';
 
	/**
	 * maximum image width
	 *
	 * @var integer
	 */
	protected $maxWidth = 100;
 
	/**
	 * maximum image height
	 *
	 * @var integer
	 */
	protected $maxHeight = 100;
 
	/**
	 * true, to show source information in thumbnail
	 *
	 * @var boolean
	 */
	protected $appendSourceInfo = false;
 
	/**
	 * true, to prefer embedded thumbnails
	 *
	 * @var boolean
	 */
	protected $useEmbedded = true;
 
	/**
	 * true, to generate quadratic thumbnails
	 * 
	 * @var	boolean
	 */
	protected $quadratic = false;
 
	/**
	 * mime type of the thumbnail
	 *
	 * @var string
	 */
	protected $mimeType = '';
 
	/**
	 * name of the source image
	 *
	 * @var string
	 */
	protected $sourceName = '';
 
	/**
	 * width of the source image
	 * 
	 * @var	integer
	 */
	protected $sourceWidth = 0;
 
	/**
	 * height of the source image
	 * 
	 * @var	integer
	 */
	protected $sourceHeight = 0;
 
	/**
	 * file size of the source image
	 * 
	 * @var	integer
	 */
	protected $sourceSize = 0;
 
	/**
	 * height of the source information
	 * 
	 * @var	integer
	 */
	protected static $sourceInfoLineHeight = 16;
 
	/**
	 * image type of the source image
	 * 
	 * @var	integer
	 */
	protected $imageType = 0;
 
	/**
	 * Creates a new Thumbnail object.
	 * 
	 * @param	string		$sourceFile
	 */
	public function __construct($sourceFile) {
		$this->sourceFile = $sourceFile;
	}
 
	/**
	 * setup dimenstions
	 *
	 * @param	boolean		$appendSourceInfo
	 */
	public function setup($appendSourceInfo = false, $sourceName = null, $useEmbedded = true, $quadratic = false) {
		$this->appendSourceInfo = $appendSourceInfo;
		$this->useEmbedded = $useEmbedded;
		$this->quadratic = $quadratic;
		if ($this->appendSourceInfo) {
			// get source info
			if ($sourceName != null) $this->sourceName = $sourceName;
			else $this->sourceName = basename($this->sourceFile);
			list($this->sourceWidth, $this->sourceHeight, $type) = @getImageSize($this->sourceFile);
			$this->sourceSize = @filesize($sourceFile);
		}
	}
 
	/** 
	 * Creates a thumbnail picture (jpg/png) of a big image
	 * 
	 * @param	boolean 	$rescale
	 * @return	string		thumbnail 
	 */
	protected function makeThumbnail($rescale = false) {
		list($width, $height, $this->imageType) = @getImageSize($this->sourceFile);
 
		// check image size
		if ($this->checkSize($width, $height, $rescale)) {
			return false;	
		}
 
		// try to extract the embedded thumbnail first (faster)
		$thumbnail = false;
		if (!$rescale && $this->useEmbedded) {
			$thumbnail = $this->extractEmbeddedThumbnail();
		}
		if (!$thumbnail) {
			// calculate uncompressed filesize
			// and cancel to avoid a memory_limit error
			$memoryLimit = ini_get('memory_limit');
			if ($memoryLimit != '') {
				$memoryLimit = substr($memoryLimit, 0, -1) * 1024 * 1024;
				$fileSize = $width * $height * ($this->imageType == 3 ? 4 : 3);
 
				if (($fileSize * 2.1) + memory_get_usage() > ($memoryLimit)) {
					return false;
				}
			}
 
			// calculate new picture size
			$x = $y = 0;
			if ($this->quadratic) {
				$newWidth = $newHeight = $this->maxWidth;
				if ($this->appendSourceInfo) $newHeight -= self::$sourceInfoLineHeight * 2;
 
				if ($width > $height) {
					$x = ceil(($width - $height) / 2);
					$width = $height;
				}
				else {
					$y = ceil(($height - $width) / 2);
					$height = $width;
				}
			}
			else {
				$maxHeight = $this->maxHeight;
				if ($this->appendSourceInfo) $maxHeight -= self::$sourceInfoLineHeight * 2;
				if ($this->maxWidth / $width < $maxHeight / $height) {
					$newWidth = $this->maxWidth;
					$newHeight = round($height * ($newWidth / $width));
				}
				else {
					$newHeight = $maxHeight;	
					$newWidth = round($width * ($newHeight / $height));
				}
			}
 
			// resize image
			$imageResource = false;
 
			// jpeg image
			if ($this->imageType == 2 && function_exists('imagecreatefromjpeg')) {
				$imageResource = @imageCreateFromJPEG($this->sourceFile);
			}
			// gif image
			if ($this->imageType == 1 && function_exists('imagecreatefromgif')) {
				$imageResource = @imageCreateFromGIF($this->sourceFile);
			}
			// png image
			if ($this->imageType == 3 && function_exists('imagecreatefrompng')) {
				$imageResource = @imageCreateFromPNG($this->sourceFile);
			}
 
			// could not create image
			if (!$imageResource) {
				return false;
			}
 
			// resize image
			if (function_exists('imageCreateTrueColor') && function_exists('imageCopyResampled')) {
				$imageNew = @imageCreateTrueColor($newWidth, $newHeight);
				imageAlphaBlending($imageNew, false);
				@imageCopyResampled($imageNew, $imageResource, 0, 0, $x, $y, $newWidth, $newHeight, $width, $height);
				imageSaveAlpha($imageNew, true);
			}
			else if (function_exists('imageCreate') && function_exists('imageCopyResized')) {
				$imageNew = @imageCreate($newWidth, $newHeight);
				imageAlphaBlending($imageNew, false);
				@imageCopyResized($imageNew, $imageResource, 0, 0, $x, $y, $newWidth, $newHeight, $width, $height);
				imageSaveAlpha($imageNew, true);
			}
			else return false;
 
			// create thumbnail
			ob_start();
 
			if ($this->imageType == 1 && function_exists('imageGIF')) {
				@imageGIF($imageNew);
				$this->mimeType = 'image/gif';
			}
			else if (($this->imageType == 1 || $this->imageType == 3) && function_exists('imagePNG')) {
				@imagePNG($imageNew);
				$this->mimeType = 'image/png';
			}
			else if (function_exists('imageJPEG')) {
				@imageJPEG($imageNew, '', 90);
				$this->mimeType = 'image/jpeg';
			}
			else {
				return false;
			}
 
			@imageDestroy($imageNew);
			$thumbnail = ob_get_contents();
			ob_end_clean();
		}
 
		if ($thumbnail && $this->appendSourceInfo && !$rescale) {
			$thumbnail = $this->appendSourceInfo($thumbnail);
		}
 
		return $thumbnail;
	}
 
	/**
	 * Appends information about the source image to the thumbnail.
	 * 
	 * @param	string		$thumbnail
	 * @return	string
	 */
	protected function appendSourceInfo($thumbnail) {
		if (!function_exists('imageCreateFromString') || !function_exists('imageCreateTrueColor')) {
			return $thumbnail;
		}
 
		$imageSrc = imageCreateFromString($thumbnail);
 
		// get image size
		$width = imageSX($imageSrc);
		$height = imageSY($imageSrc);
 
		// increase height
		$heightDst = $height + self::$sourceInfoLineHeight * 2;
 
		// create new image
		$imageDst = imageCreateTrueColor($width, $heightDst);
		imageAlphaBlending($imageDst, false);
 
		// set background color
		$background = imageColorAllocate($imageDst, 102, 102, 102);
		imageFill($imageDst, 0, 0, $background);
 
		// copy image
		imageCopy($imageDst, $imageSrc, 0, 0, 0, 0, $width, $height);
		imageSaveAlpha($imageDst, true);
 
		// get font size
		$font = 2;
		$fontWidth = imageFontWidth($font);
		$fontHeight = imageFontHeight($font);
		$fontColor = imageColorAllocate($imageDst, 255, 255, 255);
 
		// write source info
		if($maxWidth) $this->maxWidth = $maxWidth;
		if($maxHeight) $this->maxHeight = $maxHeight;
		$line1 = $this->sourceName;
 
		// imageString supports only ISO-8859-1 encoded strings
		// if (CHARSET != 'ISO-8859-1') {
		//	$line1 = StringUtil::convertEncoding(CHARSET, 'ISO-8859-1', $line1);
		// }
 
		// truncate text if necessary
		$maxChars = floor($width / $fontWidth);
		if (strlen($line1) > $maxChars) {
			$line1 = $this->truncateSourceName($line1, $maxChars);
		}
 
		$line2 = $this->sourceWidth.'x'.$this->sourceHeight;
 
		// write line 1
		// calculate text position
		$textX = 0;
		$textY = 0;
 
		if ($fontHeight < self::$sourceInfoLineHeight) {
			$textY = intval(round((self::$sourceInfoLineHeight - $fontHeight) / 2));
		}
		if (strlen($line1) * $fontWidth < $width) {
			$textX = intval(round(($width - strlen($line1) * $fontWidth) / 2));
		}
 
		imageString($imageDst, $font, $textX, $height + $textY, $line1, $fontColor);
 
		// write line 2
		// calculate text position
		$textX = 0;
		$textY = 0;
 
		if ($fontHeight < self::$sourceInfoLineHeight) {
			$textY = self::$sourceInfoLineHeight + intval(round((self::$sourceInfoLineHeight - $fontHeight) / 2));
		}
		if (strlen($line2) * $fontWidth < $width) {
			$textX = intval(round(($width - strlen($line2) * $fontWidth) / 2));
		}
 
		imageString($imageDst, $font, $textX, $height + $textY, $line2, $fontColor);
 
 
		// output image
		ob_start();
 
		if ($this->imageType == 1 && function_exists('imageGIF')) {
			@imageGIF($imageDst);
			$this->mimeType = 'image/gif';
		}
		else if (($this->imageType == 1 || $this->imageType == 3) && function_exists('imagePNG')) {
			@imagePNG($imageDst);
			$this->mimeType = 'image/png';
		}
		else if (function_exists('imageJPEG')) {
			@imageJPEG($imageDst, '', 90);
			$this->mimeType = 'image/jpeg';
		}
		else {
			return false;
		}
 
		@imageDestroy($imageDst);
		$thumbnail = ob_get_contents();
		ob_end_clean();
 
		return $thumbnail;
	}
 
 
	/** 
	 * Extracts the embedded thumbnail picture of a jpeg or tiff image
	 * 
	 * @return	string		thumbnail 
	 */
	protected function extractEmbeddedThumbnail() {
		if (!function_exists('exif_thumbnail')) {
			return false;
		}
 
		$width = $height = $type = 0;
		$thumbnail = @exif_thumbnail($this->sourceFile, $width, $height, $type);
		if ($thumbnail && $type && $width && $height) {
			// resize the extracted thumbnail again if necessary
			// (normally the thumbnail size is set to 160px
			// which is recommended in EXIF >2.1 and DCF)
			$this->mimeType = image_type_to_mime_type($type);
			if (!$this->checkSize($width, $height) && function_exists('sys_get_temp_dir')) {
				// get temporary file name
				$this->sourceFile = tempnam(sys_get_temp_dir(), 'Tux');
 
				// create tmp file
				$fh = fopen($this->sourceFile, "w");
				fwrite($fh, $thumbnail);
				fclose($fh);
				unset($thumbnail, $tmpFile);
 
				// resize tmp file again
				return $this->makeThumbnail(true);
			}
 
			return $thumbnail;
		}
 
		return false;
	}
 
	/**
	 * Checks the size of an image.
	 */
	protected function checkSize($width, $height, $rescale = true) {
		$maxHeight = $this->maxHeight;
		if ($this->appendSourceInfo && $rescale) {
			$maxHeight -= self::$sourceInfoLineHeight * 2;
		}
 
		if ($width > $this->maxWidth || $height > $maxHeight) {
			return false;
		}
 
		return true;
	}
 
	/**
	 * Returns the mime type of the generated thumbnail.
	 * 
	 * @return	string
	 */
	public function getMimeType() {
		return $this->mimeType;
	}
 
	/**
	 * Truncates the given file name to needed length.
	 * 
	 * @param	string		$name
	 * @param	string		$maxChars
	 * @return	string
	 */
	protected static function truncateSourceName($name, $maxChars) {
		$extension = '';
		$lastPosition = strrpos($name, '.');
		if ($lastPosition !== null) {
			$extension = substr($name, $lastPosition);
			$name = substr($name, 0, $lastPosition);
			$maxChars -= strlen($extension);
		}
 
		return substr($name, 0, $maxChars - 3) . '...' . $extension;
	}
 
	/**
	 *
	 * @return boolean
	 */
	public function save($targetFile, $maxWidth = 0, $maxHeight = 0) {
		$recover = array();
		if($maxWidth) {
			$recover['maxWidth'] = $this->maxWidth;
			$this->maxWidth = $maxWidth;
		}
		if($maxHeight) {
			$recover['maxHeight'] = $this->maxHeight;
			$this->maxHeight = $maxHeight;
		}
 
		// get thumbnail
		try {
			$success = true;
			if (($thumbnailData = $this->makeThumbnail())) {
 
				// save thumbnail
				$fh = fopen($targetFile, 'w');
				fwrite($fh, $thumbnailData);
				unset($thumbnailData);
				fclose($fh);
			}
		}
		catch (Exception $e) {
			$success = false;
		}
 
		foreach($recover as $key => $val) {
			$this->$key = $val;
		}
		return $success;
	}
 
	protected static function sendLastModified($timestamp) {
		// Getting headers sent by the client.
		$headers = apache_request_headers();
 
		// Checking if the client is validating his cache and if it is current.
		if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) >= $timestamp)) {
			// this timestamp can also be used to identify the user ;) see
			// Client's cache IS current, so we just respond '304 Not Modified'.
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 304);
			exit;
		} else {
			// Image not cached or cache outdated, we respond '200 OK' and output the image.
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $timestamp).' GMT', true, 200);
		}
	}
 
	/**
	 * send header and content for the picture
	 */
	public function display($maxWidth = 100, $maxHeight = 100, $age = '3 MONTH') {
		$recover = array();
		if($maxWidth) {
			$recover['maxWidth'] = $this->maxWidth;
			$this->maxWidth = $maxWidth;
		}
		if($maxHeight) {
			$recover['maxHeight'] = $this->maxHeight;
			$this->maxHeight = $maxHeight;
		}
 
		$filemtime = @filemtime($this->sourceFile);
		$thumbnailData = $this->makeThumbnail();
		$size = strlen($thumbnailData);
 
		self::sendLastModified($filemtime);
		header('Accept-Ranges: bytes');
		header('Content-Length: '.$size);
		header('Content-Type: image/jpeg');
		header('Expires: '.gmdate('D, d M Y H:i:s', time() + strtotime($age)).' GMT');
 
		echo $thumbnailData;
 
		foreach($recover as $key => $val) {
			$this->$key = $val;
		}
	}
}
?>


2. Beispiele


2.1. Bild in meheren Größen speichern


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
require_once('Thumbnail.php');
 
// this is the source
$thumb = new Thumbnail('demo/easy-coding.png');
 
// quadratic
$thumb->save('/tmp/easy-coding.png', 150, 150);
 
// 4:3 format
$thumb->save('/tmp/easy-coding.png', 100, 75);
 
?>


3. Bild \"on the fly\" anzeigen


Den Original Bildnamen könnt ihr zum Beispiel als $_GET Parameter oder mit mod_rewrite Regeln durchleiten. Im Beispiel wird die Vorschau für das Bild "easy-coding.png" erzeugt.
Der dritte Parameter der Methode display kann einen Zeitausdruck wie "3 month" enthalten, dann wird das Bild für drei Monate im Browser Cache des Benutzers gespeichert, ohne dass es erneut angefragt wird und damit Traffickosten verursacht. Allerdings bekommt der Benutzer auf diese Weise auch nicht von Änderungen mit, deswegen sollte der Intervall je nach Anwendung besser bei "1 day" liegen.

PHP Quellcode

1
2
3
4
5
6
7
<?php
require_once('Thumbnail.php');
 
$thumb = new Thumbnail('demo/easy-coding.png');
 
// just display on the fly
$thumb->display(150, 150);


4. Demo


Die Live Demo findet ihr unter http://demo.easy-coding.de/php/thumbnail/, herunterladen könnt ihr euch den Code dann unter http://demo.easy-coding.de/php/thumbnail/download.zip

Lexikon 4.1.5, developed by www.viecode.com