Skip to content

Commit

Permalink
feat: Convert buffer image to PNG format (#17)
Browse files Browse the repository at this point in the history
* feat: Convert buffer image to PNG format

* feat: Convert buffer-formatted file to a different extension

Downloaded the 'file-type' library to determine the file extension in a buffer-formatted file

* fix: Changed the path for images
  • Loading branch information
JEM1224 authored Jan 11, 2024
1 parent feee349 commit b31eee3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@
"@actions/github": "^5.1.1",
"dayjs": "^1.11.7",
"download": "^8.0.0",
"file-type": "^19.0.0",
"gray-matter": "^4.0.3",
"mkdirp": "^2.1.3",
"sharp": "^0.33.1",
"yaml": "^2.2.1"
},
"devDependencies": {
Expand Down
30 changes: 29 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import download from 'download'
import dayjs from 'dayjs'
import {extractImages} from './extract-images'
import {formatFrontMatterValue} from './format'
import sharp from 'sharp'
import {fileTypeFromBuffer} from 'file-type'

async function run(): Promise<void> {
const token: string = core.getInput('token')
Expand Down Expand Up @@ -103,11 +105,37 @@ async function run(): Promise<void> {
let bodyText = bodyWithoutFrontMatter
const images = extractImages(bodyText)
for (const image of images) {
const newImageFilename = path.basename(image.filename)
let newImageFilename = path.basename(image.filename)
fs.writeFileSync(
path.join(dirname, newImageFilename),
await download(image.filename)
)

const imagePath = path.join(dirname, newImageFilename)
const imageExt = path.extname(image.filename).toLocaleLowerCase()

if (imageExt === '') {
const buffer = fs.readFileSync(imagePath)
const imageType = await fileTypeFromBuffer(buffer)
sharp.cache(false)

if (
imageType !== undefined &&
sharp.format.hasOwnProperty(imageType?.ext)
) {
if (imageType.ext === 'gif') {
await sharp(imagePath, {
limitInputPixels: false,
animated: true,
density: 1
}).toFile(`${imagePath}.${imageType.ext}`)
} else {
await sharp(imagePath).toFile(`${imagePath}.${imageType.ext}`)
}
newImageFilename += `.${imageType.ext}`
fs.unlinkSync(imagePath)
}
}
bodyText = bodyText.replace(
image.match,
`![${image.alt}](./${newImageFilename}${
Expand Down

0 comments on commit b31eee3

Please sign in to comment.