Skip to content

Commit

Permalink
MVP
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielJDufour committed Sep 27, 2021
1 parent 88e805d commit 7226262
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
Binary file added png-to-jpg.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 10 additions & 6 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@ const writeImage = require("./write-image");
test("jpg to png", async ({ eq }) => {
const jpg = findAndRead("flower.jpg");
const { height, width, pixels } = await readim({ data: jpg });
const png = await writeImage({ data: pixels, debug: true, format: "png", height, width });
console.log("png:", png);
fs.writeFileSync("jpg-to-png.png", png);
const result = await writeImage({ data: pixels, debug: false, format: "png", height, width });
fs.writeFileSync("jpg-to-png.png", result.data);
eq(result.height, height);
eq(result.width, width);
eq(Buffer.isBuffer(result.data), true);
});

test("png to jpg", async ({ eq }) => {
const png = findAndRead("flower.png");
const { height, width, pixels } = await readim({ data: png });
const jpg = await writeImage({ data: pixels, debug: true, format: "jpg", height, width });
console.log("jpg:", jpg);
fs.writeFileSync("png-to-jpg.jpg", jpg);
const result = await writeImage({ data: pixels, debug: false, format: "jpg", height, width });
fs.writeFileSync("png-to-jpg.jpg", result.data);
eq(result.height, height);
eq(result.width, width);
eq(Buffer.isBuffer(result.data), true);
});
10 changes: 7 additions & 3 deletions write-image.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ module.exports = async function writeImage({ data, debug = false, format, height
const imageData = toImageData({ data, height, width });
if (debug) console.log(`[write-image] image data is`, imageData);

let result;
if (format === "PNG") {
const png = new PNG({ filterType: 4, height, width });
png.data = imageData.data;
if (debug) console.log(`[write-image] png is`, png);
const buffer = PNG.sync.write(png);
return { data: buffer, height, width };
result = { data: buffer, height, width };
} else if (format === "JPG") {
const { data, height, width } = jpeg.encode(imageData, quality).data;
return { data, height, width };
const encoded = jpeg.encode(imageData, quality).data;
if (debug) console.log("`[write-image] jpeg.encode returned", encoded);
result = { data: encoded, height, width };
}
if (debug) console.log(`[write-image] returning`, result);
return result;
};

0 comments on commit 7226262

Please sign in to comment.