Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Convert buffer image to PNG format #17

Merged
merged 3 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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