Repository navigation
Expand file tree
/
Copy pathImageMagick.java
More file actions
154 lines (141 loc) · 6.2 KB
/
Copy pathImageMagick.java
File metadata and controls
154 lines (141 loc) · 6.2 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
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.cloudrun;
// [START cloudrun_imageproc_handler_setup]
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import com.google.cloud.vision.v1.SafeSearchAnnotation;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class ImageMagick {
private static final String BLURRED_BUCKET_NAME = System.getenv("BLURRED_BUCKET_NAME");
private static Storage storage = StorageOptions.getDefaultInstance().getService();
// [END cloudrun_imageproc_handler_setup]
// [START cloudrun_imageproc_handler_analyze]
// Blurs uploaded images that are flagged as Adult or Violence.
public static void blurOffensiveImages(JsonObject data) {
String fileName = data.get("name").getAsString();
String bucketName = data.get("bucket").getAsString();
BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileName).build();
// Construct URI to GCS bucket and file.
String gcsPath = String.format("gs://%s/%s", bucketName, fileName);
System.out.println(String.format("Analyzing %s", fileName));
// Construct request.
List<AnnotateImageRequest> requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
requests.add(request);
// Send request to the Vision API.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.println(String.format("Error: %s\n", res.getError().getMessage()));
return;
}
// Get Safe Search Annotations
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
System.out.println(String.format("Detected %s as inappropriate.", fileName));
blur(blobInfo);
} else {
System.out.println(String.format("Detected %s as OK.", fileName));
}
}
} catch (Exception e) {
System.out.println(String.format("Error with Vision API: %s", e.getMessage()));
}
}
// [END cloudrun_imageproc_handler_analyze]
// [START cloudrun_imageproc_handler_blur]
private static final Set<String> ALLOWED_EXTENSIONS =
Set.of(".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff");
private static String getSafeExtension(String fileName) {
if (fileName != null) {
int lastDot = fileName.lastIndexOf('.');
if (lastDot >= 0 && lastDot < fileName.length() - 1) {
String ext = fileName.substring(lastDot).toLowerCase(Locale.ROOT);
if (ALLOWED_EXTENSIONS.contains(ext)) {
return ext;
}
}
}
return ".png";
}
// Blurs the file described by blobInfo using ImageMagick,
// and uploads it to the blurred bucket.
public static void blur(BlobInfo blobInfo) throws IOException {
String bucketName = blobInfo.getBucket();
String fileName = blobInfo.getName();
String extension = getSafeExtension(fileName);
// Download image to a safely generated temporary file to prevent path traversal
// and ImageMagick argument injection from untrusted object names.
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Files.createTempFile("download-", extension);
Path upload = Files.createTempFile("blurred-", extension);
try {
blob.downloadTo(download);
// Construct the command.
List<String> args =
List.of("convert", download.toString(), "-blur", "0x8", upload.toString());
try {
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
process.waitFor();
} catch (Exception e) {
System.out.println(String.format("Error: %s", e.getMessage()));
}
// Upload image to blurred bucket.
BlobId blurredBlobId = BlobId.of(BLURRED_BUCKET_NAME, fileName);
BlobInfo blurredBlobInfo =
BlobInfo.newBuilder(blurredBlobId).setContentType(blob.getContentType()).build();
try {
byte[] blurredFile = Files.readAllBytes(upload);
Blob blurredBlob = storage.create(blurredBlobInfo, blurredFile);
System.out.println(
String.format("Blurred image uploaded to: gs://%s/%s", BLURRED_BUCKET_NAME, fileName));
} catch (Exception e) {
System.out.println(String.format("Error in upload: %s", e.getMessage()));
}
} finally {
// Remove images from fileSystem
Files.deleteIfExists(download);
Files.deleteIfExists(upload);
}
}
}
// [END cloudrun_imageproc_handler_blur]