-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathimgur_uploader.php
102 lines (87 loc) · 3.14 KB
/
imgur_uploader.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
<?php
include 'settings.php';
$client_id = $i_i;
$externalImg = $_POST['urlToImg'];
if (!isset($_FILES['chximg']) && !isset($externalImg) || $_FILES['chximg']['error'] == UPLOAD_ERR_NO_FILE && !isset($externalImg)) {
echo json_encode(array("error" => "No file uploaded and no external image URL provided"));
die();
} else {
if (isset($_FILES['chximg']) && !empty($_FILES['chximg']['tmp_name'])) {
$image = file_get_contents($_FILES['chximg']['tmp_name']);
if ($image === false) {
echo json_encode(array("error" => "Failed to read uploaded file"));
die();
}
} elseif (!empty($externalImg)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $externalImg);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$image = curl_exec($ch);
if ($image === false) {
echo json_encode(array("error" => "Failed to download image from external URL"));
die();
}
curl_close($ch);
} else {
echo json_encode(array("error" => "No file uploaded and no external image URL provided"));
die();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Client-ID ' . $client_id
));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'image' => base64_encode($image)
));
$reply = curl_exec($ch);
if (curl_error($ch)) {
die('Curl error: ' . curl_error($ch));
}
curl_close($ch);
$reply = json_decode($reply);
$link = $reply->data->link;
$ext = strtolower(pathinfo($link, PATHINFO_EXTENSION));
if ($ext === 'png') {
$pngImage = imagecreatefrompng($link);
$width = imagesx($pngImage);
$height = imagesy($pngImage);
$hasTransparency = false;
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgba = imagecolorat($pngImage, $x, $y);
$colors = imagecolorsforindex($pngImage, $rgba);
if ($colors['alpha'] > 0) {
$hasTransparency = true;
break 2;
}
}
}
imagedestroy($pngImage);
if ($hasTransparency) {
$thumbnail = $link;
} else {
$thumbnail = substr_replace($link, 'l', -4, 0);
}
} elseif ($ext === 'gif') {
$thumbnail = $link;
} else {
$thumbnail = substr_replace($link, 'l', -4, 0);
}
if ($reply->data->width > 265) {
$maxWidth = 265;
} else {
$maxWidth = $reply->data->width;
}
$resized_width = $maxWidth;
$resized_height = ($reply->data->height / $reply->data->width) * $resized_width;
$resized_height = bcdiv($resized_height, 1, 2);
$arr = array(
"link" => $link,
"clientHeight" => $resized_height,
"thumbnail" => $thumbnail
);
echo json_encode($arr);
}