Hướng dẫn nodejs image processing
Step 1: Create Node Express Project
Khởi tạo Show
Tiếp theo cần cài đặt 1 số package sau
Giải thích:
Tiếp theo cần cài đặt nodemon, khi save code tự động Restart Server NodeJS
Để sử dụng nodemon, ta cần Thêm vào file package.json code như sau:
Step 2: Create a server.js file.Tạo file
Tại terminal, run npm start.
nó output như dưới, là chúng ta đã tạo server nodejs ok rồi.
Step 3: Configure the EJS templating engine.để sử dụng EJS teamplate, thêm code sau vào file server.js
create folder public/index.html
Step 4: Configure Express Router.Tạo file router.js
require file route trong file server.js
Step 5: Create a form.Tạo form upload, create file index.ejs trong folder
view form: http://localhost:3000/upload Step 6: Create file upload middlewaređể xử lý multipart/form-data trong Node.js, chúng ta đã cài đặt multer, để xử dụng nó chúng ta cần tạo file uploadMiddleware.js với nội dung như sau
Step 7: Resize the imagenhư đã đề cập ở trên để thay đổi kích thước hình ảnh JPEG, PNG, WebP và TIFF chúng ta sẽ sử dụng Sharp vs nodejs, chúng ta sẽ resize lại kích thước của ảnh nhưng vẫn giữ đc chất của nó. Để sử dụng Sharp, ta tạo file Resize.js trong folder root và thêm đoạn mã sau.
Trong file trên, mình đã tạo class là Resize, và config đường dẫn đến thư mục upload trong folder public. Step 8: Save the image in the file system
Step 9: Demo uploadMàn hình upload Click upload File uploaded Step 10: SummaryNhư vậy mình đã hướng dẫn sử dụng lib sharp, để upload vs resize ảnh trong nodejs, hy vọng bài viết sẽ giúp ích cho bạn, Thank you so much !
|