-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_resizeorig.module
More file actions
311 lines (298 loc) · 8.99 KB
/
image_resizeorig.module
File metadata and controls
311 lines (298 loc) · 8.99 KB
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
<?php
/**
* @file
* Hooks and functions for Image Resize Original.
*/
/**
* Implements hook_entity_presave().
*/
function image_resizeorig_entity_presave($entity, $type) {
if ($entity->isNew() || $type != 'file') {
return;
}
// Keep original timestamp if custom property is set.
if (isset($entity->keepTimestamp)) {
$original = $entity->original;
$entity->timestamp = $original->timestamp;
}
}
/**
* Custom callback to actually resize the image.
*
* @param File $file
* The File entity.
* @param string $maxwidth
* Width to scale the image down to.
*
* @return bool
* True in case of success, false in case of broken image.
*/
function _image_resizeorig_resize_image(File $file, $maxwidth) {
$image = image_load($file->uri);
if ($image) {
image_scale($image, $maxwidth);
image_save($image, $file->uri);
$file->keepTimestamp = TRUE;
// Saving the file updates metadata and also fires hook_entity_presave().
$file->save();
return TRUE;
}
return FALSE;
}
/**
* Check file type, mime, dimension and resize if necessary.
*
* @param string $fid
* Numeric File ID as string.
* @param string $maxwidth
* Number of pixels, as string.
*
* @return bool
* Whether the file needed processing or not.
*/
function image_resizeorig_evaluate_file($fid, $maxwidth) {
if ($file = file_load($fid)) {
if ($file->type != 'image') {
return FALSE;
}
$possible_mimes = array(
'image/jpeg',
'image/png',
'image/webp',
);
$mime = $file->filemime;
// Just in case.
if (!in_array($mime, $possible_mimes) || !isset($file->width)) {
return FALSE;
}
// Safety guard against out-of-memory fatal error.
$pixelcount = $file->width * $file->height;
if ($pixelcount > _image_resizeorig_max_pixels()) {
return FALSE;
}
// Nothing to do.
if ($file->width <= $maxwidth) {
return FALSE;
}
return _image_resizeorig_resize_image($file, $maxwidth);
}
return FALSE;
}
/**
* Estimate how many pixels an image can have to not exhaust available memory.
*
* @return int
* Maximum number of pixels to safely handle.
*/
function _image_resizeorig_max_pixels() {
$max_pixel_count = &backdrop_static(__FUNCTION__);
if (!isset($max_pixel_count)) {
$memory_limit = ini_get('memory_limit');
if ($memory_limit == -1) {
// Just to return a high number for the unlikely case.
$max_pixel_count = 1024 * 1024 * 1024;
}
else {
$memory_limit_bytes = parse_size($memory_limit);
// Leave some MB for other tasks.
$available_bytes = $memory_limit_bytes - 20 * 1024 * 1024;
// Assumptions: 3 color channels, factor 1.8.
$max_pixel_count = $available_bytes / (3 * 1.8);
}
}
return (int) $max_pixel_count;
}
/**
* Fetch candidates from file_managed.
*
* We can not use "width" from file_metadata, as that's serialized, so we just
* skip over small file sizes here.
*
* @param array $mime_types
* Array of mime types like "image/jpeg".
* @param int $min_size
* Minimum size in bytes.
*
* @return array
* Array of File entity IDs.
*/
function image_resizeorig_fetch_candidate_fids(array $mime_types, $min_size) {
$fids = db_select('file_managed', 'fm')
->fields('fm', array('fid'))
->condition('type', 'image')
->condition('filemime', $mime_types, 'IN')
->condition('filesize', $min_size, '>')
->execute()
->fetchCol();
return $fids;
}
/**
* Implements hook_menu().
*/
function image_resizeorig_menu() {
$items = array();
$items['admin/content/image-resize-massupdate'] = array(
'title' => 'Mass resize images',
'type' => MENU_LOCAL_TASK,
'page callback' => 'backdrop_get_form',
'page arguments' => array('image_resizeorig_mass_resize_form'),
'access arguments' => array('bypass file access'),
);
return $items;
}
/**
* Form callback on admin/content/image-resize-massupdate.
*/
function image_resizeorig_mass_resize_form($form, $form_state) {
$form = array();
$info = array();
$info[] = t('Resize original images to free some disk space.');
$info[] = t('When resizing huge amounts of very large images, processing may take a while.');
$info[] = t('This action cannot be undone.');
$form['intro'] = array(
'#type' => 'help',
'#markup' => implode('<br>', $info),
);
$form['maxwidth'] = array(
'#type' => 'number',
'#title' => t('Max width'),
'#min' => 500,
'#max' => 3000,
'#default_value' => 1600,
'#required' => TRUE,
'#field_suffix' => 'px',
'#description' => t('Images wider than this will get scaled down.'),
);
$form['mimetypes'] = array(
'#type' => 'checkboxes',
'#title' => t('Mime types'),
'#options' => array(
'image/jpeg' => 'JPEG',
'image/png' => 'PNG',
'image/webp' => 'WEBP',
),
'#default_value' => array('image/jpeg'),
'#description' => t('Caution, PNG can sometimes end up with a larger file size after scaling.'),
'#required' => TRUE,
);
$form['minsize'] = array(
'#type' => 'select',
'#title' => t('Minimum file size'),
'#description' => t('Only consider file sizes bigger than that.'),
'#options' => array(
'524288' => '0.5',
'1048576' => '1',
'2097152' => '2',
'3145728' => '3',
'4194304' => '4',
'5242880' => '5',
),
'#default_value' => '1048576',
'#field_suffix' => 'MB',
'#required' => TRUE,
);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#submit' => array('image_resizeorig_mass_resize_form_submit'),
);
return $form;
}
/**
* Submit callback for image_resizeorig_mass_resize_form().
*/
function image_resizeorig_mass_resize_form_submit($form, &$form_state) {
$mime_types = array_filter($form_state['values']['mimetypes']);
$min_size = (int) $form_state['values']['minsize'];
$fids = image_resizeorig_fetch_candidate_fids(array_keys($mime_types), $min_size);
$maxwidth = $form_state['values']['maxwidth'];
image_resizeorig_mass_update($fids, $maxwidth);
$form_state['redirect'] = 'admin/content/files';
}
/**
* Run mass update in batches or loop, depending on count.
*
* @param array $fids
* Array of File IDs.
* @param string $maxwidth
* Number of pixels to resize larger images to.
*/
function image_resizeorig_mass_update(array $fids, $maxwidth) {
if (count($fids) > 10) {
$params = array($fids, $maxwidth);
$batch = array(
'operations' => array(
array('_image_resizeorig_mass_update_batch_process', $params),
),
'finished' => '_image_resizeorig_mass_update_batch_finished',
'title' => t('Processing'),
'progress_message' => '',
'error_message' => t('The update has encountered an error.'),
);
batch_set($batch);
}
else {
$file_fids = array();
foreach ($fids as $fid) {
$processed = image_resizeorig_evaluate_file($fid, $maxwidth);
if ($processed) {
$file_fids[] = $fid;
}
}
backdrop_set_message(t('The update has been performed.'));
$message = format_plural(count($file_fids), '1 item needed processing.', '@count items needed processing.');
backdrop_set_message($message);
}
}
/**
* Process callback for the batch.
*
* @param array $fids
* Array of File entity IDs.
* @param string $maxwidth
* Max width to resize images to if necessary.
* @param array $context
* An array of contextual key/values, provided by reference.
*/
function _image_resizeorig_mass_update_batch_process(array $fids, $maxwidth, array &$context) {
if (!isset($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['max'] = count($fids);
$context['sandbox']['fids'] = $fids;
}
// Process files by groups of 5.
$count = min(5, count($context['sandbox']['fids']));
for ($i = 1; $i <= $count; $i++) {
$fid = array_shift($context['sandbox']['fids']);
$processed = image_resizeorig_evaluate_file($fid, $maxwidth);
// Store result for a message in the finished callback.
if ($processed) {
$context['results'][] = $fid;
}
$context['sandbox']['progress']++;
}
// Inform the batch engine that we are not finished, and provide an estimation
// of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
/**
* Set a message after batch processing.
*
* @param bool $success
* Whether the batch mass update operation succeeded.
* @param array $results
* Array of File entity IDs that actually got processed.
*/
function _image_resizeorig_mass_update_batch_finished($success, array $results) {
if ($success) {
backdrop_set_message(t('The update has been performed.'));
$message = format_plural(count($results), '1 item needed processing.', '@count items needed processing.');
backdrop_set_message($message);
}
else {
backdrop_set_message(t('An error occurred and processing did not complete.'), 'error');
}
}