Форум программистов, компьютерный форум, киберфорум
PHP: ООП
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.55/11: Рейтинг темы: голосов - 11, средняя оценка - 4.55
0 / 0 / 0
Регистрация: 13.07.2011
Сообщений: 54
1

Класс Ресайз изображения

16.08.2011, 14:26. Показов 2277. Ответов 7
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте,помогите решить вопрос
есть класс
PHP
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
  
        Class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;
 
            function __construct($fileName)
            {
                // *** Open up the file
                $this->image = $this->openImage($fileName);
 
                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }
 
            ## --------------------------------------------------------
 
            private function openImage($file)
            {
                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));
 
                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }
                return $img;
            }
 
            ## --------------------------------------------------------
 
            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);
 
                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];
 
 
                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
 
 
                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }
 
            ## --------------------------------------------------------
            
            private function getDimensions($newWidth, $newHeight, $option)
            {
 
               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }
 
            ## --------------------------------------------------------
 
            private function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }
 
            private function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }
 
            private function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }
 
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }
 
            ## --------------------------------------------------------
 
            private function getOptimalCrop($newWidth, $newHeight)
            {
 
                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;
 
                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }
 
                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;
 
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }
 
            ## --------------------------------------------------------
 
            private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
 
                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);
 
                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }
 
            ## --------------------------------------------------------
 
            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                $extension = strtolower($extension);
 
                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;
 
                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;
 
                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);
 
                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;
 
                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;
 
                    // ... etc
 
                    default:
                        // *** No extension - No save.
                        break;
                }
 
                imagedestroy($this->imageResized);
            }
 
 
            ## --------------------------------------------------------
 
        }
Вызываю класс и изменяю размер картинки так
PHP
1
2
3
4
include("classes/resize_class.php");
$resizeObj = new resize('images/cars/large/input.jpg');
$resizeObj -> resizeImage(150, 100, 0);
$resizeObj -> saveImage('images/cars/large/output.jpg', 100);
150 = ширина
100 = высота
Возможно ли, назначать ширину и что бы высота генерировалась автоматом?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
16.08.2011, 14:26
Ответы с готовыми решениями:

Ресайз изображения
Есть изображение, такого вида: увеличиваю(делаю ресайз) его в 2 раза в paint.net-e .превращаю в...

Изменить качество изображения или ресайз php
Подскажите пожалуйста, есть код, который грузит файл на сервер. &lt;?php $uploaddir =...

Перемещение и ресайз изображения
Доброго всем дня. Мне нужен контрол. Внутри него помещается изображение которое можно вращать и...

Ресайз изображения с привязкой div
Подскажите пожалуйста формулу Есть изображение 1700x1158 div имеет позицию left: 150px; top: 256px;...

7
13208 / 6596 / 1041
Регистрация: 10.01.2008
Сообщений: 15,069
16.08.2011, 15:02 2
Цитата Сообщение от dogmar Посмотреть сообщение
Возможно ли, назначать ширину и что бы высота генерировалась автоматом?
Так а в чем сложность? У Вас же почти так и происходит. Сделайте аргументы ширины и высоты необязательными.
PHP
1
public function resizeImage($newWidth=null, $newHeight=null, $option="auto")
и вызывайте как-то так:
PHP
1
2
3
4
$resizeObj -> resizeImage(150, null, "auto");
$resizeObj -> resizeImage(150); // то же самое
$resizeObj -> resizeImage(null, 100);
$resizeObj -> resizeImage(); // а если оба параметра null, то ошибку генерировать
0
0 / 0 / 0
Регистрация: 13.07.2011
Сообщений: 54
16.08.2011, 15:08  [ТС] 3
Цитата Сообщение от Vovan-VE Посмотреть сообщение
Так а в чем сложность? У Вас же почти так и происходит. Сделайте аргументы ширины и высоты необязательными.
PHP
1
public function resizeImage($newWidth=null, $newHeight=null, $option="auto")
и вызывайте как-то так:
PHP
1
2
3
4
$resizeObj -> resizeImage(150, null, "auto");
$resizeObj -> resizeImage(150); // то же самое
$resizeObj -> resizeImage(null, 100);
$resizeObj -> resizeImage(); // а если оба параметра null, то ошибку генерировать
Заменил строчку на
public function resizeImage($newWidth=null, $newHeight=null, $option="auto"

Вызываю так, $resizeObj -> resizeImage(100);, и все генерирует, но при этом пишет ошибку

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in Z:\home\dvig.ru\www\users\resize-class.php on line 76

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in Z:\home\dvig.ru\www\users\resize-class.php on line 77

Warning: imagejpeg(): supplied argument is not a valid Image resource in Z:\home\dvig.ru\www\users\resize-class.php on line 217

Warning: imagedestroy(): supplied argument is not a valid Image resource in Z:\home\dvig.ru\www\users\resize-class.php on line 246
0
13208 / 6596 / 1041
Регистрация: 10.01.2008
Сообщений: 15,069
16.08.2011, 19:30 4
Цитата Сообщение от dogmar Посмотреть сообщение
Заменил строчку и все генерирует, но при этом пишет ошибку
Ну так само собой. Остальной-то код кто будет править, чтобы он работал соответствующим образом?
Сложность у Вас конкретно в чем?
0
0 / 0 / 0
Регистрация: 13.07.2011
Сообщений: 54
17.08.2011, 10:36  [ТС] 5
Цитата Сообщение от Vovan-VE Посмотреть сообщение
Ну так само собой. Остальной-то код кто будет править, чтобы он работал соответствующим образом?
Сложность у Вас конкретно в чем?
Вы так удивляетесь как будто я опытный программист,и не могу решить элементарные задачки,я новичок, я знаю что у меня есть класс, и есть код его вызова,сложность в том, что я не могу подправить его под свои нужды,и вы мне помогли,и все работает просто отлично спасибо, но выдает ошибку которую я написал выше,самому подправить код, не хватает знаний пока((

Добавлено через 14 часов 31 минуту
кто подправит? за +1 спасибо
0
Веб-мастер
89 / 89 / 19
Регистрация: 11.08.2011
Сообщений: 674
18.08.2011, 01:10 6
Если вы показываете изображение с помощью img. То всё очень просто!
<img scr='link' width='100'>
heaight атрибут не надо. Он автоматически будет регулироваться. =)
0
463 / 463 / 23
Регистрация: 17.08.2011
Сообщений: 1,488
18.08.2011, 05:44 7
Цитата Сообщение от dogmar Посмотреть сообщение
Здравствуйте,помогите решить вопрос
Возможно ли, назначать ширину и что бы высота генерировалась автоматом?
Держи.
PHP
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
<?php
 
                Class resize
                {
                        // *** Class variables
                        private $image;
                        private $width;
                        private $height;
                        private $imageResized;
 
                        function __construct($fileName)
                        {
                                // *** Open up the file
                                $this->image = $this->openImage($fileName);
 
                            // *** Get width and height
                            $this->width  = imagesx($this->image);
                            $this->height = imagesy($this->image);
                        }
 
                        ## --------------------------------------------------------
 
                        private function openImage($file)
                        {
                                // *** Get extension
                                $extension = strtolower(strrchr($file, '.'));
 
                                switch($extension)
                                {
                                        case '.jpg':
                                        case '.jpeg':
                                                $img = @imagecreatefromjpeg($file);
                                                break;
                                        case '.gif':
                                                $img = @imagecreatefromgif($file);
                                                break;
                                        case '.png':
                                                $img = @imagecreatefrompng($file);
                                                break;
                                        default:
                                                $img = false;
                                                break;
                                }
                                return $img;
                        }
 
                        ## --------------------------------------------------------
 
                        public function resizeImage($newWidth, $option="auto")
                        {
                                // *** Get optimal width and height - based on $option
                                $newHeight = (imagesx($this->image)<imagesy($this->image))?
                                imagesx($this->image)/imagesy($this->image)*$newWidth:
                                imagesy($this->image)/imagesx($this->image)*$newWidth;
                                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);
 
                                $optimalWidth  = $optionArray['optimalWidth'];
                                $optimalHeight = $optionArray['optimalHeight'];
 
 
                                // *** Resample - create image canvas of x, y size
                                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
 
 
                                // *** if option is 'crop', then crop too
                                if ($option == 'crop') {
                                        $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                                }
                        }
 
                        ## --------------------------------------------------------
                        
                        private function getDimensions($newWidth, $newHeight, $option)
                        {
 
                           switch ($option)
                                {
                                        case 'exact':
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $newHeight;
                                                break;
                                        case 'portrait':
                                                $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                                $optimalHeight= $newHeight;
                                                break;
                                        case 'landscape':
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                                break;
                                        case 'auto':
                                                $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                                                $optimalWidth = $optionArray['optimalWidth'];
                                                $optimalHeight = $optionArray['optimalHeight'];
                                                break;
                                        case 'crop':
                                                $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                                                $optimalWidth = $optionArray['optimalWidth'];
                                                $optimalHeight = $optionArray['optimalHeight'];
                                                break;
                                }
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function getSizeByFixedHeight($newHeight)
                        {
                                $ratio = $this->width / $this->height;
                                $newWidth = $newHeight * $ratio;
                                return $newWidth;
                        }
 
                        private function getSizeByFixedWidth($newWidth)
                        {
                                $ratio = $this->height / $this->width;
                                $newHeight = $newWidth * $ratio;
                                return $newHeight;
                        }
 
                        private function getSizeByAuto($newWidth, $newHeight)
                        {
                                if ($this->height < $this->width)
                                // *** Image to be resized is wider (landscape)
                                {
                                        $optimalWidth = $newWidth;
                                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                }
                                elseif ($this->height > $this->width)
                                // *** Image to be resized is taller (portrait)
                                {
                                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                        $optimalHeight= $newHeight;
                                }
                                else
                                // *** Image to be resizerd is a square
                                {
                                        if ($newHeight < $newWidth) {
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                        } else if ($newHeight > $newWidth) {
                                                $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                                $optimalHeight= $newHeight;
                                        } else {
                                                // *** Sqaure being resized to a square
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $newHeight;
                                        }
                                }
 
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function getOptimalCrop($newWidth, $newHeight)
                        {
 
                                $heightRatio = $this->height / $newHeight;
                                $widthRatio  = $this->width /  $newWidth;
 
                                if ($heightRatio < $widthRatio) {
                                        $optimalRatio = $heightRatio;
                                } else {
                                        $optimalRatio = $widthRatio;
                                }
 
                                $optimalHeight = $this->height / $optimalRatio;
                                $optimalWidth  = $this->width  / $optimalRatio;
 
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
                        {
                                // *** Find center - this will be used for the crop
                                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
 
                                $crop = $this->imageResized;
                                //imagedestroy($this->imageResized);
 
                                // *** Now crop from center to exact requested size
                                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        public function saveImage($savePath, $imageQuality="100")
                        {
                                // *** Get extension
                        $extension = strrchr($savePath, '.');
                        $extension = strtolower($extension);
 
                                switch($extension)
                                {
                                        case '.jpg':
                                        case '.jpeg':
                                                if (imagetypes() & IMG_JPG) {
                                                        imagejpeg($this->imageResized, $savePath, $imageQuality);
                                                }
                                                break;
 
                                        case '.gif':
                                                if (imagetypes() & IMG_GIF) {
                                                        imagegif($this->imageResized, $savePath);
                                                }
                                                break;
 
                                        case '.png':
                                                // *** Scale quality from 0-100 to 0-9
                                                $scaleQuality = round(($imageQuality/100) * 9);
 
                                                // *** Invert quality setting as 0 is best, not 9
                                                $invertScaleQuality = 9 - $scaleQuality;
 
                                                if (imagetypes() & IMG_PNG) {
                                                         imagepng($this->imageResized, $savePath, $invertScaleQuality);
                                                }
                                                break;
 
                                        // ... etc
 
                                        default:
                                                // *** No extension - No save.
                                                break;
                                }
 
                                imagedestroy($this->imageResized);
                        }
 
 
                        ## --------------------------------------------------------
 
                }
// Вызов
$resizeObj = new resize('input.jpg');
$resizeObj -> resizeImage(100, 0);
$resizeObj -> saveImage('output.jpg', 10);
 
 
 
?>
измененный кусок кода строка 53:
PHP
1
2
3
$newHeight = (imagesx($this->image)<imagesy($this->image))?
              imagesx($this->image)/imagesy($this->image)*$newWidth:
              imagesy($this->image)/imagesx($this->image)*$newWidth;
1
0 / 0 / 0
Регистрация: 13.07.2011
Сообщений: 54
18.08.2011, 13:03  [ТС] 8
Цитата Сообщение от Денис Н. Посмотреть сообщение
Держи.
PHP
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
<?php
 
                Class resize
                {
                        // *** Class variables
                        private $image;
                        private $width;
                        private $height;
                        private $imageResized;
 
                        function __construct($fileName)
                        {
                                // *** Open up the file
                                $this->image = $this->openImage($fileName);
 
                            // *** Get width and height
                            $this->width  = imagesx($this->image);
                            $this->height = imagesy($this->image);
                        }
 
                        ## --------------------------------------------------------
 
                        private function openImage($file)
                        {
                                // *** Get extension
                                $extension = strtolower(strrchr($file, '.'));
 
                                switch($extension)
                                {
                                        case '.jpg':
                                        case '.jpeg':
                                                $img = @imagecreatefromjpeg($file);
                                                break;
                                        case '.gif':
                                                $img = @imagecreatefromgif($file);
                                                break;
                                        case '.png':
                                                $img = @imagecreatefrompng($file);
                                                break;
                                        default:
                                                $img = false;
                                                break;
                                }
                                return $img;
                        }
 
                        ## --------------------------------------------------------
 
                        public function resizeImage($newWidth, $option="auto")
                        {
                                // *** Get optimal width and height - based on $option
                                $newHeight = (imagesx($this->image)<imagesy($this->image))?
                                imagesx($this->image)/imagesy($this->image)*$newWidth:
                                imagesy($this->image)/imagesx($this->image)*$newWidth;
                                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);
 
                                $optimalWidth  = $optionArray['optimalWidth'];
                                $optimalHeight = $optionArray['optimalHeight'];
 
 
                                // *** Resample - create image canvas of x, y size
                                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
 
 
                                // *** if option is 'crop', then crop too
                                if ($option == 'crop') {
                                        $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                                }
                        }
 
                        ## --------------------------------------------------------
                        
                        private function getDimensions($newWidth, $newHeight, $option)
                        {
 
                           switch ($option)
                                {
                                        case 'exact':
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $newHeight;
                                                break;
                                        case 'portrait':
                                                $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                                $optimalHeight= $newHeight;
                                                break;
                                        case 'landscape':
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                                break;
                                        case 'auto':
                                                $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                                                $optimalWidth = $optionArray['optimalWidth'];
                                                $optimalHeight = $optionArray['optimalHeight'];
                                                break;
                                        case 'crop':
                                                $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                                                $optimalWidth = $optionArray['optimalWidth'];
                                                $optimalHeight = $optionArray['optimalHeight'];
                                                break;
                                }
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function getSizeByFixedHeight($newHeight)
                        {
                                $ratio = $this->width / $this->height;
                                $newWidth = $newHeight * $ratio;
                                return $newWidth;
                        }
 
                        private function getSizeByFixedWidth($newWidth)
                        {
                                $ratio = $this->height / $this->width;
                                $newHeight = $newWidth * $ratio;
                                return $newHeight;
                        }
 
                        private function getSizeByAuto($newWidth, $newHeight)
                        {
                                if ($this->height < $this->width)
                                // *** Image to be resized is wider (landscape)
                                {
                                        $optimalWidth = $newWidth;
                                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                }
                                elseif ($this->height > $this->width)
                                // *** Image to be resized is taller (portrait)
                                {
                                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                        $optimalHeight= $newHeight;
                                }
                                else
                                // *** Image to be resizerd is a square
                                {
                                        if ($newHeight < $newWidth) {
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                                        } else if ($newHeight > $newWidth) {
                                                $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                                                $optimalHeight= $newHeight;
                                        } else {
                                                // *** Sqaure being resized to a square
                                                $optimalWidth = $newWidth;
                                                $optimalHeight= $newHeight;
                                        }
                                }
 
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function getOptimalCrop($newWidth, $newHeight)
                        {
 
                                $heightRatio = $this->height / $newHeight;
                                $widthRatio  = $this->width /  $newWidth;
 
                                if ($heightRatio < $widthRatio) {
                                        $optimalRatio = $heightRatio;
                                } else {
                                        $optimalRatio = $widthRatio;
                                }
 
                                $optimalHeight = $this->height / $optimalRatio;
                                $optimalWidth  = $this->width  / $optimalRatio;
 
                                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
                        {
                                // *** Find center - this will be used for the crop
                                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
 
                                $crop = $this->imageResized;
                                //imagedestroy($this->imageResized);
 
                                // *** Now crop from center to exact requested size
                                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
                        }
 
                        ## --------------------------------------------------------
 
                        public function saveImage($savePath, $imageQuality="100")
                        {
                                // *** Get extension
                        $extension = strrchr($savePath, '.');
                        $extension = strtolower($extension);
 
                                switch($extension)
                                {
                                        case '.jpg':
                                        case '.jpeg':
                                                if (imagetypes() & IMG_JPG) {
                                                        imagejpeg($this->imageResized, $savePath, $imageQuality);
                                                }
                                                break;
 
                                        case '.gif':
                                                if (imagetypes() & IMG_GIF) {
                                                        imagegif($this->imageResized, $savePath);
                                                }
                                                break;
 
                                        case '.png':
                                                // *** Scale quality from 0-100 to 0-9
                                                $scaleQuality = round(($imageQuality/100) * 9);
 
                                                // *** Invert quality setting as 0 is best, not 9
                                                $invertScaleQuality = 9 - $scaleQuality;
 
                                                if (imagetypes() & IMG_PNG) {
                                                         imagepng($this->imageResized, $savePath, $invertScaleQuality);
                                                }
                                                break;
 
                                        // ... etc
 
                                        default:
                                                // *** No extension - No save.
                                                break;
                                }
 
                                imagedestroy($this->imageResized);
                        }
 
 
                        ## --------------------------------------------------------
 
                }
// Вызов
$resizeObj = new resize('input.jpg');
$resizeObj -> resizeImage(100, 0);
$resizeObj -> saveImage('output.jpg', 10);
 
 
 
?>
измененный кусок кода строка 53:
PHP
1
2
3
$newHeight = (imagesx($this->image)<imagesy($this->image))?
              imagesx($this->image)/imagesy($this->image)*$newWidth:
              imagesy($this->image)/imagesx($this->image)*$newWidth;
Спасибо.

Если вы показываете изображение с помощью img. То всё очень просто!
<img scr='link' width='100'>
heaight атрибут не надо. Он автоматически будет регулироваться. =)
Вы немножко не о том...)

Добавлено через 1 час 35 минут
Кстати говоря, заметил что странно рейсайзит допустим есть картинка
ширина = 334
высота = 500
классом ставлю ширину 100, высота должна получиться 149
а получается 66. из-за чего такое происходит?

Добавлено через 26 минут
сейчас еще проверил. и вобщем понял

PHP
1
2
3
4
// Вызов
$resizeObj = new resize('input.jpg');
$resizeObj -> resizeImage(100, 0);
$resizeObj -> saveImage('output.jpg', 10);
Здесь он устанавливает Высоту а ширину подгоняет, мне нужно наоборот) Хееепл

Добавлено через 18 минут
____________

...
все решил,спасибо всем.

$resizeObj = new resize("img.jpg");
$resizeObj -> resizeImage(100, 'landscape');
$resizeObj -> saveImage("img.jpg", 100);
0
18.08.2011, 13:03
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
18.08.2011, 13:03
Помогаю со студенческими работами здесь

Класс изображения img
можно ли переменную класса сделать изображением ? если можно подскажите где поискать, в инете уже...

Вывод изображения класс Image
практикуюсь поставил себе цель сделать игру используя по максимуму принципы ООП и вот так вот...

Объединить методы обработки изображения в класс
Добрый день, помогите пожалуйста создать класс для следующих методов Инверсия Graphics::TBitmap...

Класс изображения по умолчанию проставлялся в изображении?
Добрый день. Можно ли где то прописать класс изображения чтобы он по умолчанию проставлялся во...

Изменить размер изображения не используя класс Bitmap
Здравствуйте! Можно ли как-то изменить размер изображения не используя класс Bitmap? При...

Подправить класс для высокочастотной фильтрации изображения
Здравствуйте. Есть класс, который должен входное gray scale изображение обрабатывать одной из 3х...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru