summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMalf Furious <m@lfurio.us>2017-04-19 00:29:19 -0400
committerMalf Furious <m@lfurio.us>2017-04-19 00:29:19 -0400
commit065c8bbb637954c47259e312ef87667e8d281497 (patch)
treef084e05b90d3169adffe1b1741eb4577b940301e
parentf75939bab55a9d8b77e4ba26f569f266625ad3d5 (diff)
downloadscrott-065c8bbb637954c47259e312ef87667e8d281497.tar.gz
scrott-065c8bbb637954c47259e312ef87667e8d281497.zip
Add image cropping logic
User-supplied head images will need to be square in their dimensions, so that bootstrap displays them correctly. This function will crop image files after they are uploaded to the server.
Diffstat (limited to '')
-rw-r--r--app/class/image.php70
1 files changed, 70 insertions, 0 deletions
diff --git a/app/class/image.php b/app/class/image.php
new file mode 100644
index 0000000..6b73cae
--- /dev/null
+++ b/app/class/image.php
@@ -0,0 +1,70 @@
+<?php
+
+/*
+ * SCROTT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * For more information, please refer to UNLICENSE
+ */
+
+/*
+ * This file defines custom image manipulation routines for Scrott. All
+ * are available in the global namespace.
+ */
+
+/*
+ * Mappings from image MIME types to PHP open/write functions
+ */
+$_IMG_OPEN_FUNCS['image/jpeg'] = "imagecreatefromjpeg";
+$_IMG_OPEN_FUNCS['image/jpg'] = "imagecreatefromjpeg";
+$_IMG_OPEN_FUNCS['image/png'] = "imagecreatefrompng";
+
+$_IMG_WRITE_FUNCS['image/jpeg'] = "imagejpeg";
+$_IMG_WRITE_FUNCS['image/jpg'] = "imagejpeg";
+$_IMG_WRITE_FUNCS['image/png'] = "imagepng";
+
+/*
+ * Open the given image and crop it, such that the result is a square
+ * image whose side length is equal to the smaller of the original
+ * dimensions and whose area is centered on the area of the original
+ * image. The resulting image is written to the same path as provided,
+ * overwriting the image.
+ */
+function imageSquareCrop(string $uri) : bool
+{
+ global $_IMG_OPEN_FUNCS;
+ global $_IMG_WRITE_FUNCS;
+
+ $mime = mime_content_type($uri);
+ $img = $_IMG_OPEN_FUNCS[$mime]($uri);
+
+ if ($img === false)
+ return false;
+
+ $wid = imagesx($img);
+ $hei = imagesy($img);
+
+ $rec = array();
+ $rec['width'] = min($wid, $hei);
+ $rec['height'] = $rec['width'];
+ $rec['y'] = ($hei / 2) - ($rec['height'] / 2);
+ $rec['x'] = ($wid / 2) - ($rec['width'] / 2);
+
+ $cropped = imagecrop($img, $rec);
+ imagedestroy($img);
+
+ if ($cropped === false)
+ return false;
+
+ $ret = $_IMG_WRITE_FUNCS[$mime]($cropped, $uri);
+ imagedestroy($cropped);
+
+ return $ret;
+}
+
+?>