-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
ImageMagick.java
136 lines (125 loc) · 5.45 KB
/
ImageMagick.java
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
/*
* 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.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
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]
// 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();
// Download image
Blob blob = storage.get(BlobId.of(bucketName, fileName));
Path download = Paths.get("/tmp/", fileName);
blob.downloadTo(download);
// Construct the command.
List<String> args = new ArrayList<>();
args.add("convert");
args.add(download.toString());
args.add("-blur");
args.add("0x8");
Path upload = Paths.get("/tmp/", "blurred-" + fileName);
args.add(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()));
}
// Remove images from fileSystem
Files.delete(download);
Files.delete(upload);
}
}
// [END cloudrun_imageproc_handler_blur]