Skip to content

Instantly share code, notes, and snippets.

@tandevmode
Created June 2, 2021 02:13
Show Gist options
  • Save tandevmode/1475833d5e5ea6d7a6cd6a0075a66dc3 to your computer and use it in GitHub Desktop.
Save tandevmode/1475833d5e5ea6d7a6cd6a0075a66dc3 to your computer and use it in GitHub Desktop.
const uploadAndProcessImg = async (event, city) => {
// ดึงรูปของผู้ใช้ที่ส่งมาจาก LINE
const url = `${LINE_CONTENT_API}/${event.message.id}/content`;
const originalImage = await axios({
method: "get",
headers: LINE_HEADER,
url: url,
responseType: "arraybuffer"
});
// เซฟรูปผู้ใช้ลงเครื่องและทำการอัพโหลดไว้ที่ Cloud Storage
const filename = event.timestamp;
const originalLocalFile = path.join(os.tmpdir(), filename + ".jpg");
fs.writeFileSync(originalLocalFile, originalImage.data);
const originalImageUrl = await uploadImage(event, originalLocalFile, filename + ".jpg");
// ดึงรูปสถานที่เที่ยวจาก Unsplash
const backgroundImage = await axios({
method: "get",
url: UNSPLASH_API + city + ",landscape",
responseType: "arraybuffer"
});
// เซฟรูปสถานที่เที่ยวลงเครื่องและทำการอัพโหลดไว้ที่ Cloud Storage
const backgroundLocalFile = path.join(os.tmpdir(), filename + "-bg.jpg");
fs.writeFileSync(backgroundLocalFile, backgroundImage.data);
const backgroundImageUrl = await uploadImage(event, backgroundLocalFile, filename + "-bg.jpg");
// เรียกใช้ Remove bg API โดยส่งรูปของผู้ใช้กับสถานที่เที่ยว
const result = await axios({
method: "post",
headers: {
"accept": "application/json",
"Content-Type": "application/json",
"X-API-Key": "your-removebg-api-key"
},
url: REMOVE_BG_API,
data: JSON.stringify({
size: "preview",
image_file: "",
semitransparency: "true",
position: "original",
bg_color: "",
scale: "original",
image_url: originalImageUrl,
roi: "0% 0% 100% 100%",
crop: "false",
channels: "rgba",
bg_image_url: backgroundImageUrl,
format: "auto",
type: "auto",
crop_margin: "0",
add_shadow: "false",
type_level: 1
})
});
// ได้ผลลัพธ์กลับมาเป็น base64 ต้องสร้าง buffer จาก base64
const bufferResult = Buffer.from(result.data.data.result_b64, "base64");
// เซฟรูปที่ได้จาก Remove bg ลงเครื่องและทำการอัพโหลดไว้ที่ Cloud Storage
const resultLocalFile = path.join(os.tmpdir(), filename + "-result.jpg");
fs.writeFileSync(resultLocalFile, bufferResult);
const resultImageUrl = await uploadImage(event, resultLocalFile, filename + "-result.jpg");
// ลบไฟล์ temp เมื่ออัพโหลดเรียบร้อย
fs.unlinkSync(originalLocalFile);
fs.unlinkSync(backgroundLocalFile);
fs.unlinkSync(resultLocalFile);
return resultImageUrl;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment