Spaces:
Running
Running
File size: 17,597 Bytes
ca46a75 |
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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
# API Documentation
## TOC
- [Before You Start: Launch the Backend Service](#before-you-start-launch-the-backend-service)
- [Interface Function Descriptions](#interface-function-descriptions)
- [cURL Request Example](#curl-request-examples)
- [Python Request Example](#python-request-example)
- [Python Requests Method](#1️⃣-python-requests-method)
- [Python Script Method](#2️⃣-python-script-request-method)
- [Java Request Example](#java-request-example)
- [Javascript Request Example](#javascript-request-examples)
## Before You Start: Launch the Backend Service
Before making API requests, please run the backend service:
```bash
python deploy_api.py
```
<br>
## Interface Function Descriptions
### 1. Generate ID Photo (Transparent Background)
Interface Name: `idphoto`
The `Generate ID Photo` interface logic involves sending an RGB image and receiving a standard ID photo and a high-definition ID photo:
- **High-Definition ID Photo**: An ID photo made according to the aspect ratio of `size`, with the filename being `output_image_dir` appended with `_hd` suffix.
- **Standard ID Photo**: A photo with dimensions equal to `size`, scaled from the high-definition ID photo, with the filename being `output_image_dir`.
It should be noted that both generated photos are transparent (RGBA four-channel images). To produce a complete ID photo, the following `Add Background Color` interface is also required.
> Q: Why is this design used?
> A: In actual products, users often need to frequently switch background colors to preview effects. Providing a transparent background image and allowing the front-end JavaScript code to synthesize the color offers a better user experience.
### 2. Add Background Color
Interface Name: `add_background`
The `Add Background Color` interface logic involves sending an RGBA image, adding a background color based on `color`, and synthesizing a JPG image.
### 3. Generate 6-inch Layout Photo
Interface Name: `generate_layout_photos`
The `Generate 6-inch Layout Photo` interface logic involves sending an RGB image (usually an ID photo after adding a background color), arranging the photos according to `size`, and then generating a 6-inch layout photo.
<br>
## cURL Request Examples
cURL is a command-line tool used to transfer data using various network protocols. Below are examples of how to use cURL to call these APIs.
### 1. Generate ID Photo (Transparent Background)
```bash
curl -X POST "http://127.0.0.1:8080/idphoto" \
-F "input_image=@demo/images/test.jpg" \
-F "height=413" \
-F "width=295"
```
### 2. Add Background Color
```bash
curl -X POST "http://127.0.0.1:8080/add_background" \
-F "input_image=@test.png" \
-F "color=638cce" \
-F "kb=200"
```
### 3. Generate Six-Inch Layout Photo
```bash
curl -X POST "http://127.0.0.1:8080/generate_layout_photos" \
-F "input_image=@test.jpg" \
-F "height=413" \
-F "width=295" \
-F "kb=200"
```
## Python Request Example
### 1️⃣ Python Requests Method
#### 1. Generate ID Photo (Transparent Background)
```python
import requests
url = "http://127.0.0.1:8080/idphoto"
input_image_path = "images/test.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"height": 413, "width": 295}
response = requests.post(url, files=files, data=data).json()
# response is a JSON dictionary containing status, image_base64_standard, and image_base64_hd
print(response)
```
#### 2. Add Background Color
```python
import requests
url = "http://127.0.0.1:8080/add_background"
input_image_path = "test.png"
files = {"input_image": open(input_image_path, "rb")}
data = {"color": '638cce', 'kb': None}
response = requests.post(url, files=files, data=data).json()
# response is a JSON dictionary containing status and image_base64
print(response)
```
#### 3. Generate 6-inch Layout Photo
```python
import requests
url = "http://127.0.0.1:8080/generate_layout_photos"
input_image_path = "test.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"height": 413, "width": 295, "kb": 200}
response = requests.post(url, files=files, data=data).json()
# response is a JSON dictionary containing status and image_base64
print(response)
```
<br>
### 2️⃣ Python Script Request Method
```bash
python requests_api.py -u <URL> -t <TYPE> -i <INPUT_IMAGE_DIR> -o <OUTPUT_IMAGE_DIR> [--height <HEIGHT>] [--width <WIDTH>] [-c <COLOR>] [-k <KB>]
```
#### Parameter Descriptions
##### Basic Parameters
- `-u`, `--url`
- **Description**: The URL of the API service.
- **Default Value**: `http://127.0.0.1:8080`
- `-t`, `--type`
- **Description**: The type of API request, with optional values being `idphoto`, `add_background`, and `generate_layout_photos`. They represent ID photo creation, transparent image background addition, and layout photo generation, respectively.
- **Default Value**: `idphoto`
- `-i`, `--input_image_dir`
- **Description**: The path of the input image.
- **Required**: Yes
- **Example**: `./input_images/photo.jpg`
- `-o`, `--output_image_dir`
- **Description**: The path to save the image.
- **Required**: Yes
- **Example**: `./output_images/processed_photo.jpg`
##### Optional Parameters
- `--height`
- **Description**: The height of the output size for the standard ID photo.
- **Default Value**: 413
- `--width`
- **Description**: The width of the output size for the standard ID photo.
- **Default Value**: 295
- `-c`, `--color`
- **Description**: Adds a background color to the transparent image, in Hex format (e.g., #638cce), only effective when the type is `add_background`.
- **Default Value**: `638cce`
- `-k`, `--kb`
- **Description**: The KB value of the output photo, only effective when the type is `add_background` or `generate_layout_photos`, and no setting is made when the value is None.
- **Default Value**: `None`
- **Example**: `50`
#### 1. Generate ID Photo (Transparent Background)
```bash
python requests_api.py \
-u http://127.0.0.1:8080 \
-t idphoto \
-i ./photo.jpg \
-o ./idphoto.png \
--height 413 \
--width 295
```
#### 2. Add Background Color
```bash
python requests_api.py \
-u http://127.0.0.1:8080 \
-t add_background \
-i ./idphoto.png \
-o ./idphoto_with_background.jpg \
-c 638cce \
-k 50
```
#### 3. Generate 6-inch Layout Photo
```bash
python requests_api.py \
-u http://127.0.0.1:8080 \
-t generate_layout_photos \
-i ./idphoto_with_background.jpg \
-o ./layout_photo.jpg \
--height 413 \
--width 295 \
-k 200
```
#### Request Failure Scenarios
- The request fails if more than one face is detected in the photo.
## Java Request Example
### Add Maven Dependency
```java
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
```
### Running the Code
#### 1. Generate ID Photo (Transparent Background)
```java
/**
* Generate ID Photo (Transparent Background) /idphoto interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestIdPhoto(String inputImageDir) throws IOException {
String url = BASE_URL+"/idphoto";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("height","413");
paramMap.put("width","295");
// Contains status, image_base64_standard, and image_base64_hd
return HttpUtil.post(url, paramMap);
}
```
#### 2. Add Background Color
```java
/**
* Add Background Color /add_background interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestAddBackground(String inputImageDir) throws IOException {
String url = BASE_URL+"/add_background";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("color","638cce");
paramMap.put("kb","200");
// Response is a JSON dictionary containing status and image_base64
return HttpUtil.post(url, paramMap);
}
```
#### 3. Generate 6-inch Layout Photo
```java
/**
* Generate 6-inch Layout Photo /generate_layout_photos interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestGenerateLayoutPhotos(String inputImageDir) throws IOException {
String url = BASE_URL+"/generate_layout_photos";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("height","413");
paramMap.put("width","295");
paramMap.put("kb","200");
// Response is a JSON dictionary containing status and image_base64
return HttpUtil.post(url, paramMap);
}
```
#### 4. Summary
```java
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @author: qingshuang
* @createDate: 2024/09/05
* @description: Java generate ID photo, test case
*/
public class Test {
/**
* Interface address
*/
private final static String BASE_URL = "http://127.0.0.1:8080";
/**
* Generate ID Photo (Transparent Background) /idphoto interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestIdPhoto(String inputImageDir) throws IOException {
String url = BASE_URL+"/idphoto";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("height","413");
paramMap.put("width","295");
return HttpUtil.post(url, paramMap);
}
/**
* Add Background Color /add_background interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestAddBackground(String inputImageDir) throws IOException {
String url = BASE_URL+"/add_background";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("color","638cce");
paramMap.put("kb","200");
return HttpUtil.post(url, paramMap);
}
/**
* Generate 6-inch Layout Photo /generate_layout_photos interface
* @param inputImageDir File address
* @return
* @throws IOException
*/
public static String requestGenerateLayoutPhotos(String inputImageDir) throws IOException {
String url = BASE_URL+"/generate_layout_photos";
// Create file object
File inputFile = new File(inputImageDir);
Map<String, Object> paramMap=new HashMap<>();
paramMap.put("input_image",inputFile);
paramMap.put("height","413");
paramMap.put("width","295");
paramMap.put("kb","200");
return HttpUtil.post(url, paramMap);
}
/**
* Generate ID Photo (Transparent Background)
* @param inputImageDir Source file address
* @param outputImageDir Output file address
* @throws IOException
*/
private static void requestIdPhotoToImage(String inputImageDir, String outputImageDir) throws IOException {
String res =requestIdPhoto(inputImageDir);
// Convert to JSON
JSONObject response= JSONUtil.parseObj(res);
if(response.getBool("status")){// Request interface success
String image_base64_standard= response.getStr("image_base64_standard");
String image_base64_hd =response.getStr("image_base64_hd");
String[] outputImageDirArr= StringUtils.split(outputImageDir,".");
// Base64 save as image
FileUtils.writeByteArrayToFile(new File(outputImageDirArr[0]+"_standard."+outputImageDirArr[1]), Base64.getDecoder().decode(image_base64_standard));
FileUtils.writeByteArrayToFile(new File(outputImageDirArr[0]+"_hd."+outputImageDirArr[1]), Base64.getDecoder().decode(image_base64_hd));
}
}
/**
* Add Background Color
* @param inputImageDir Source file address
* @param outputImageDir Output file address
* @throws IOException
*/
private static void requestAddBackgroundToImage(String inputImageDir, String outputImageDir) throws IOException {
String res =requestAddBackground(inputImageDir);
// Convert to JSON
JSONObject response= JSONUtil.parseObj(res);
if(response.getBool("status")){// Request interface success
String image_base64= response.getStr("image_base64");
String[] outputImageDirArr= StringUtils.split(outputImageDir,".");
// Base64 save as image
FileUtils.writeByteArrayToFile(new File(outputImageDirArr[0]+"_background."+outputImageDirArr[1]), Base64.getDecoder().decode(image_base64));
}
}
/**
* Generate 6-inch Layout Photo
* @param inputImageDir Source file address
* @param outputImageDir Output file address
* @throws IOException
*/
private static void requestGenerateLayoutPhotosToImage(String inputImageDir, String outputImageDir) throws IOException {
String res =requestGenerateLayoutPhotos(inputImageDir);
// Convert to JSON
JSONObject response= JSONUtil.parseObj(res);
if(response.getBool("status")){// Request interface success
String image_base64= response.getStr("image_base64");
String[] outputImageDirArr= StringUtils.split(outputImageDir,".");
// Base64 save as image
FileUtils.writeByteArrayToFile(new File(outputImageDirArr[0]+"_layout."+outputImageDirArr[1]), Base64.getDecoder().decode(image_base64));
}
}
public static void main(String[] args) {
try {
// Generate ID Photo (Transparent Background)
requestIdPhotoToImage("C:\\Users\\Administrator\\Desktop\\1111.jpg","C:\\Users\\Administrator\\Desktop\\2222.png");
// Add Background Color
requestAddBackgroundToImage("C:\\Users\\Administrator\\Desktop\\2222_hd.png","C:\\Users\\Administrator\\Desktop\\idphoto_with_background.jpg");
// Generate 6-inch Layout Photo
requestGenerateLayoutPhotosToImage("C:\\Users\\Administrator\\Desktop\\1111.jpg","C:\\Users\\Administrator\\Desktop\\2222.png");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
## JavaScript Request Examples
In JavaScript, we can use the `fetch` API to send HTTP requests. Below are examples of how to call these APIs using JavaScript.
### 1. Generate ID Photo (Transparent Background)
```javascript
async function generateIdPhoto(inputImagePath, height, width) {
const url = "http://127.0.0.1:8080/idphoto";
const formData = new FormData();
formData.append("input_image", new File([await fetch(inputImagePath).then(res => res.blob())], "test.jpg"));
formData.append("height", height);
formData.append("width", width);
const response = await fetch(url, {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);
return result;
}
// Example call
generateIdPhoto("images/test.jpg", 413, 295).then(response => {
console.log(response);
});
```
### 2. Add Background Color
```javascript
async function addBackground(inputImagePath, color, kb) {
const url = "http://127.0.0.1:8080/add_background";
const formData = new FormData();
formData.append("input_image", new File([await fetch(inputImagePath).then(res => res.blob())], "test.png"));
formData.append("color", color);
formData.append("kb", kb);
const response = await fetch(url, {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);
return result;
}
// Example call
addBackground("test.png", "638cce", 200).then(response => {
console.log(response);
});
```
### 3. Generate Six-Inch Layout Photo
```javascript
async function generateLayoutPhotos(inputImagePath, height, width, kb) {
const url = "http://127.0.0.1:8080/generate_layout_photos";
const formData = new FormData();
formData.append("input_image", new File([await fetch(inputImagePath).then(res => res.blob())], "test.jpg"));
formData.append("height", height);
formData.append("width", width);
formData.append("kb", kb);
const response = await fetch(url, {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);
return result;
}
// Example call
generateLayoutPhotos("test.jpg", 413, 295, 200).then(response => {
console.log(response);
});
``` |