I'm using jpeg-js library to decode an image, apply my own greyscale filter, and encode it back. But unfortunately every vertical picture I process for some reason is rotated and saved horizontally (while horizontal images preserve its correct rotation and are totally ok). Here's my code:
function greyscale(width, height, data, bytesPerPixel, imageName) {
const bwPixelData = Buffer.alloc(data.length)
for (let vrt = 0; vrt < height; vrt++) {
for (let hrz = 0; hrz < width; hrz++) {
const offset = (vrt * width + hrz) * bytesPerPixel
const red = data[offset]
const green = data[offset + 1]
const blue = data[offset + 2]
const bwPixel = Math.round((red + green + blue) / 3.0)
bwPixelData[offset] = bwPixel
bwPixelData[offset + 1] = bwPixel
bwPixelData[offset + 2] = bwPixel
}
}
const filteredImageName = encodeImage(bwPixelData, width, height, imageName)
return filteredImageName
}
exports.decodeImage = function(name, path) {
if (name.match(/.*\.jpe?g/i)){
const jpegData = fs.readFileSync(path)
return jpeg.decode(jpegData)
} else {
throw new Error('Unsupported Media Type')
}
}
exports.encodeImage = function(data, width, height, imageName) {
const filteredImageName = `outfile-${imageName}`
const rawImageData = {
data: data,
width: width,
height: height,
}
const jpegImageData = jpeg.encode(rawImageData, 50)
try {
fs.writeFileSync(`${outputPath}/${filteredImageName}`, jpegImageData.data);
console.log('File written successfully');
} catch (error) {
console.error('Error writing file:', error);
}
return filteredImageName
}
At first I thought that the problem might be hidden in the greyscale function and how I process pixels. So I tried to decode, encode, and save back an original, unfiltered, vertical photo, which had lead to the same result: unexpected rotation.
Have you ever faced a problem like this and does anyone know how to fix it? It's also important to me to use a pure js implementation instead of libraries like Sharp