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

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

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

Студворк — интернет-сервис помощи студентам
Здравствуйте,помогите решить вопрос
есть класс
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
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
16.08.2011, 14:26
Ответы с готовыми решениями:

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

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

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

7
 Аватар для Vovan-VE
13210 / 6599 / 1041
Регистрация: 10.01.2008
Сообщений: 15,069
16.08.2011, 15:02
Цитата Сообщение от 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  [ТС]
Цитата Сообщение от 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
 Аватар для Vovan-VE
13210 / 6599 / 1041
Регистрация: 10.01.2008
Сообщений: 15,069
16.08.2011, 19:30
Цитата Сообщение от dogmar Посмотреть сообщение
Заменил строчку и все генерирует, но при этом пишет ошибку
Ну так само собой. Остальной-то код кто будет править, чтобы он работал соответствующим образом?
Сложность у Вас конкретно в чем?
0
0 / 0 / 0
Регистрация: 13.07.2011
Сообщений: 54
17.08.2011, 10:36  [ТС]
Цитата Сообщение от Vovan-VE Посмотреть сообщение
Ну так само собой. Остальной-то код кто будет править, чтобы он работал соответствующим образом?
Сложность у Вас конкретно в чем?
Вы так удивляетесь как будто я опытный программист,и не могу решить элементарные задачки,я новичок, я знаю что у меня есть класс, и есть код его вызова,сложность в том, что я не могу подправить его под свои нужды,и вы мне помогли,и все работает просто отлично спасибо, но выдает ошибку которую я написал выше,самому подправить код, не хватает знаний пока((

Добавлено через 14 часов 31 минуту
кто подправит? за +1 спасибо
0
Веб-мастер
 Аватар для Maksimchikfull
89 / 89 / 19
Регистрация: 11.08.2011
Сообщений: 674
18.08.2011, 01:10
Если вы показываете изображение с помощью img. То всё очень просто!
<img scr='link' width='100'>
heaight атрибут не надо. Он автоматически будет регулироваться. =)
0
 Аватар для Денис Н.
463 / 463 / 23
Регистрация: 17.08.2011
Сообщений: 1,488
18.08.2011, 05:44
Цитата Сообщение от 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  [ТС]
Цитата Сообщение от Денис Н. Посмотреть сообщение
Держи.
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
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
18.08.2011, 13:03
Помогаю со студенческими работами здесь

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

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

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

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

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


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

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru