Skip to content

Commit

Permalink
adding image optimizer
Browse files Browse the repository at this point in the history
  • Loading branch information
DerLev committed Aug 1, 2023
1 parent eadda66 commit 55a69aa
Show file tree
Hide file tree
Showing 6 changed files with 375 additions and 20 deletions.
4 changes: 3 additions & 1 deletion functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
"dependencies": {
"@google-cloud/functions-framework": "^3.3.0",
"@google-cloud/logging": "^10.5.0",
"@google-cloud/storage": "^6.12.0",
"@google/events": "^5.4.0",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"eslint": "^8.46.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-import": "^2.28.0",
"sharp": "^0.32.4",
"typescript": "^5.1.6"
},
"engines": {
Expand All @@ -23,6 +25,6 @@
"scripts": {
"lint": "eslint --fix --ext .js,.ts .",
"build": "tsc",
"gcp-build": "yarn build"
"gcp-build": "yarn add sharp && yarn build"
}
}
3 changes: 3 additions & 0 deletions functions/src/helpers/gCloudClients.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {Storage} from "@google-cloud/storage";

export const storage = new Storage();
2 changes: 1 addition & 1 deletion functions/src/storage/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from "./moveToMainBucket";
export * from "./optimizeImages";
9 changes: 0 additions & 9 deletions functions/src/storage/moveToMainBucket.ts

This file was deleted.

42 changes: 42 additions & 0 deletions functions/src/storage/optimizeImages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type {
StorageObjectData,
} from "@google/events/cloud/storage/v1/StorageObjectData";
import {storage} from "../helpers/gCloudClients";
import * as sharp from "sharp";

const options = {
destBucket: "derlev.xyz",
};

export const optimizeImages = async (
event: StorageObjectData
) => {
if (
!event.bucket ||
!event.name ||
!event.contentType?.startsWith("image/")
) return;

const file = storage.bucket(event.bucket)
.file(event.name);

const fileRead = file.createReadStream();

const sharpRezise = sharp().webp({force: false, quality: 80, effort: 6})
.png({force: false, compressionLevel: 7, effort: 7})
.jpeg({force: false, quality: 80, mozjpeg: true})
.gif({force: false})
.tiff({force: false, quality: 80});

const sharpStream = fileRead.pipe(sharpRezise);

const destFile = storage.bucket(options.destBucket)
.file(event.name)
.createWriteStream();

const writeDestStream = sharpStream.pipe(destFile);

writeDestStream.on("close", async () => {
await file.delete();
});
};
Loading

0 comments on commit 55a69aa

Please sign in to comment.