Skip to content

Instantly share code, notes, and snippets.

@Enelar
Last active January 30, 2016 02:30
Show Gist options
  • Save Enelar/338cac4694d4458f998f to your computer and use it in GitHub Desktop.
Save Enelar/338cac4694d4458f998f to your computer and use it in GitHub Desktop.
Cut photoshop 100-200 MB psd files into 50KB jpeg.
<meta http-equiv="refresh" content="5"/>
<?php
include('phpa2o.php');
include('phpsql/oneline.php');
phpsql\OneLineConfig("pgsql://postgres@localhost/plov");
$trans = db::Begin();
db::Query("LOCK files IN ACCESS EXCLUSIVE MODE");
$res = db::Query("SELECT * FROM files WHERE finish IS NULL AND (start IS NULL OR now() - start > '5 min'::interval) LIMIT 1", [], true);
if (!$res())
exit("DONE");
db::Query("UPDATE files SET start=now() WHERE file=$1", [$res->file]);
$trans->Commit();
if (!file_exists("origins/{$res->file}.png"))
die ("File not found");
$im = imagecreatefrompng("origins/{$res->file}.png");
function Cut($im)
{
$width = imagesx($im);
$height = imagesy($im);
$dim = [$width, $height, 0, 0];
$max_alpha = -1;
set_time_limit(60*30);
for ($y = 0; $y < $height; $y++)
for ($x = 0; $x < $width; $x++)
{
$rgba = imagecolorat($im, $x, $y);
$colors = imagecolorsforindex($im, $rgba);
if ($colors["alpha"] > $max_alpha)
{
$max_alpha = $colors["alpha"];
$x = -1;
$y = 0;
continue;
}
if ($colors["alpha"] == $max_alpha)
continue;
if ($x < $dim[0])
$dim[0] = $x;
if ($y < $dim[1])
$dim[1] = $y;
if ($x > $dim[2])
$dim[2] = $x;
if ($y > $dim[3])
$dim[3] = $y;
}
$new_width = $dim[2] - $dim[0];
$new_height = $dim[3] - $dim[1];
var_dump($dim);
$out = imagecreatetruecolor($new_width, $new_height);
imagealphablending($out, false);
imagesavealpha($out, true);
imagecopy ($out, $im, 0, 0, $dim[0], $dim[1], $new_width, $new_height);
return $out;
}
function Resize($im, $maxw)
{
$width = imagesx($im);
$height = imagesy($im);
$coef = $maxw / $width;
if ($width < $maxw)
$coef = 1;
$new_height = $coef * $height;
$out = imagecreatetruecolor($maxw, $new_height);
imageinterlace($out, 1);
imagealphablending($out, true);
//imagesavealpha($out, true);
$white = imagecolorallocate($out, 254, 254, 254);
imagefill($out, 0, 0, $white);
imagecopyresampled($out, $im, 0, 0, 0, 0, $maxw, $new_height, $width, $height);
return $out;
}
//$out = Cut($im);
// $did = imagepng($out, "results/{$res->file}.png", 9);
$out = Resize($im, 1024);
$did = imagejpeg($out, "results/{$res->file}.jpg");
if ($did)
{
db::Query("UPDATE files SET finish=now() WHERE file=$1", [$res->file]);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment