How to use the read function from jimp

Find comprehensive JavaScript jimp.read code examples handpicked from public code repositorys.

jimp.read is a method in the Jimp image processing library that loads an image file from disk or a URL.

1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
case '!crop':{
  if (msg.attachments.length>0&&msg.attachments[0].content_type.startsWith('image/')){
    var attachmentsUrls = msg.attachments.map((u)=>{return u.proxy_url})
    attachmentsUrls.forEach((url)=>{
      log('cropping '+url)
      jimp.read(url,(err,img)=>{
        if(err){log('Error during cropping'.bgRed);log(err)}
        img.autocrop()
        var newMsg='<@'+msg.author.id+'> used `!crop`'
        if(!creditsDisabled){
fork icon22
star icon101
watch icon0

+ 19 other calls in file

132
133
134
135
136
137
138
139
140
141

 global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())

const reSize = async (buffer, ukur1, ukur2) => {
    return new Promise(async (resolve, reject) => {
       var baper = await Jimp.read(buffer);
       var ab = await baper.resize(ukur1, ukur2).getBufferAsync(Jimp.MIME_JPEG)
       resolve(ab)
    })
 }
fork icon218
star icon72
watch icon5

+ 14 other calls in file

How does jimp.read work?

jimp.read is an asynchronous method that takes a single argument: the path or URL of the image file to be loaded. When called, jimp.read creates a new Jimp image object and loads the image data from the specified file or URL. The method uses the built-in fs module to read files from disk, and it can also load images from remote URLs using the request package. The image format is automatically detected from the file extension, and Jimp supports a wide variety of common image formats such as JPEG, PNG, BMP, and GIF. Once the image data is loaded, it is stored in a Jimp object that can be used for a variety of image manipulation tasks such as cropping, resizing, and applying filters. The Jimp object also provides access to the individual pixels of the image for more advanced image processing tasks. Note that since jimp.read is asynchronous, it returns a Promise that resolves to the loaded Jimp object. This means that you can use async/await syntax or .then() syntax to work with the loaded image data.

667
668
669
670
671
672
673
674
675
676
let editToken = randomstring.generate();
let eventImageFilename = "";
let isPartOfEventGroup = false;
if (req.files && Object.keys(req.files).length !== 0) {
  let eventImageBuffer = req.files.imageUpload.data;
  eventImageFilename = await Jimp.read(eventImageBuffer)
    .then(img => {
      img
        .resize(920, Jimp.AUTO) // resize
        .quality(80) // set JPEG quality
fork icon26
star icon192
watch icon5

+ 59 other calls in file

499
500
501
502
503
504
505
506
507
508
509


async function charaWrite(img_url, data, target_img, response = undefined, mes = 'ok'){
    try {
        // Read the image, resize, and save it as a PNG into the buffer
        let image = null;
        await jimp.read(img_url).then(img => {
            return img
                .resize(400, 600)
                .getBufferAsync(jimp.MIME_PNG);
        }).then(data => {
fork icon19
star icon24
watch icon3

+ 5 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const Jimp = require("jimp");

async function resizeImage(inputPath, outputPath, width, height) {
  try {
    // Load the image from file using jimp.read
    const image = await Jimp.read(inputPath);

    // Resize the image using the resize method
    image.resize(width, height);

    // Save the resized image to disk
    await image.writeAsync(outputPath);

    console.log(
      `Resized image to ${width}x${height} and saved to ${outputPath}`
    );
  } catch (error) {
    console.error(`Error resizing image: ${error}`);
  }
}

// Call the resizeImage function with the input and output paths, as well as the desired dimensions
resizeImage("./input.jpg", "./output.jpg", 500, 500);

In this example, jimp.read is used to load an image file at the path ./input.jpg. The resize method is then used to resize the image to a width and height of 500 pixels, and the resulting image is saved to the file at ./output.jpg. Note that the resizeImage function is declared as async and uses await to wait for Jimp.read and image.writeAsync to complete.

5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
  didOpen: () => {
    Swal.showLoading();
  },
});

await Jimp.read(original_image_path)
  .then(async (file) => {
    if (!fs.existsSync(destination_image_path)) {
      fs.mkdirSync(destination_image_path, { recursive: true });
    }
fork icon9
star icon22
watch icon9

+ 3 other calls in file

262
263
264
265
266
267
268
269
270
271
* @returns
*/

conn.resize = async (buffer, uk1, uk2) => {
	return new Promise(async(resolve, reject) => {
		var baper = await jimp.read(buffer);
		var ab = await baper.resize(uk1, uk2).getBufferAsync(jimp.MIME_JPEG)
		resolve(ab)
	})
}
fork icon7
star icon6
watch icon1

+ 15 other calls in file

59
60
61
62
63
64
65
66
67
68
if (!foundBuild) {
  throw new NotFoundError(`No build found with id ${buildId}`);
}
build = foundBuild;
const promises = [
  jimp.read(req.file.path)
    .then((image) => image
      .scaleToFit(300, 300)
      .quality(72)
      .getBase64Async(image.getMIME())),
fork icon6
star icon7
watch icon4

+ 4 other calls in file

132
133
134
135
136
137
138
139
140
141
142


exports.url = (url) => {
    return url.match(new RegExp(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%.+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%+.~#?&/=]*)/, 'gi'))
}
exports.generateProfilePicture = async(buffer) => {
	const jimp_1 = await jimp.read(buffer);
	const resz = jimp_1.getWidth() > jimp_1.getHeight() ? jimp_1.resize(550, jimp.AUTO) : jimp_1.resize(jimp.AUTO, 650)
	const jimp_2 = await jimp.read(await resz.getBufferAsync(jimp.MIME_JPEG));
	return {
	  img: await resz.getBufferAsync(jimp.MIME_JPEG)
fork icon28
star icon6
watch icon2

+ 2 other calls in file

94
95
96
97
98
99
100
101
102
103
 * Converts either a PNG or JPEG to MIP and returns the buffer.
 * @param {Buffer|string} input - PNG/JPG data/path
 * @returns {Buffer} - Mip data
 */
static import = async input => {
    const image = await Jimp.read(input);
    const dimensions = (image.bitmap.width < 128) ? 64 : 128;
    const texture = Buffer.alloc(0x480 + (dimensions * dimensions));

    image.resize(dimensions, dimensions);
fork icon0
star icon4
watch icon2

+ 7 other calls in file

175
176
177
178
179
180
181
182
183
184
    spritePath: tmp + '/sprite.png',
    stylesheetPath: tmp + '/sprite.css',
    layout: 'horizontal',
    compositor: 'jimp'
}, function(err) {
    Jimp.read(tmp + '/sprite.png', function(err, lenna) {
        if (err) throw err;
        lenna.quality(60).write(output);
        rm(tmp, function() {
            resolve(output);
fork icon26
star icon0
watch icon1

+ 7 other calls in file

654
655
656
657
658
659
660
661
662
663
664
665
});


async function charaWrite(img_url, data, target_img, response = undefined, mes = 'ok') {
    try {
        // Read the image, resize, and save it as a PNG into the buffer
        const rawImg = await jimp.read(img_url);
        const image = await rawImg.cover(400, 600).getBufferAsync(jimp.MIME_PNG);


        // Get the chunks
        const chunks = extract(image);
fork icon2
star icon1
watch icon0

+ 5 other calls in file

1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
// online path + no local resource
// online path + in change log

// convert new map png to jpg
await new Promise((resolve, reject) => {
    Jimp.read(pngPath)
        .then(img => {
            console.log(` getting ${fileName} map image...`);
            return img.quality(70) // set JPEG quality
                .write(outputPath + ".jpg"); // save
fork icon1
star icon3
watch icon1

+ 11 other calls in file

112
113
114
115
116
117
118
119
120
121
122
  res.send({ message: "success" });
};


async function cropImage(origin, destination, x, y, width, height) {
  return new Promise(async (resolve, reject) => {
    Jimp.read(origin)
      .then((image) => {
        resolve(
          image
            .clone()
fork icon1
star icon1
watch icon0

67
68
69
70
71
72
73
74
75
76
if (id !== req.user._id.toString()) {
  res.status(401).send('Not authorized!');
  return;
}

const uploadedImage = await Jimp.read(req.file.path);
const editedImagePath = path.join(avatarsPath, req.file.filename);
await uploadedImage
  .resize(128, 128)
  .quality(70)
fork icon1
star icon1
watch icon0

+ 3 other calls in file

164
165
166
167
168
169
170
171
172
173
// img.out('-annotate').out('0').out(word);
img.out(`caption: ${word}`);
img.out('-extent').out(`${width * args.columns}x${height * args.rows}`);
img.setFormat('png');
let buf = await imToBuffer(img);
let jimg = await Jimp.read(buf);

for (let y = 0; y < args.rows; y++) {
    for (let x = 0; x < args.columns; x++) {
        let encoder = encoders[y][x];
fork icon1
star icon0
watch icon1

+ 7 other calls in file

68
69
70
71
72
73
74
75
76
77
return new Promise((res, rej) => {
  this.pixels = [];
  this.colored = [];
  this.importances = [];

  Jimp.read(this.heatmap, (err, image) => {
    if (err) { rej(err); return; }
    this.map = image;
    sizeOf(this.heatmap, (err, dimensions) => {
      if (err) { rej(err); return; }
fork icon0
star icon3
watch icon0

+ 3 other calls in file

153
154
155
156
157
158
159
160
161
162
163
};


const jimpResize = (path, i, uploadPath, filename) => {
  return new Promise((resolve, reject) => {
    try {
      Jimp.read(path, (err, image) => {
        if (err) {
          //throw err;
          console.log("jimp", err);
          return resolve(false);
fork icon0
star icon2
watch icon3

+ 19 other calls in file

205
206
207
208
209
210
211
212
213
214
215


async function ppwa(conn, m) { 
let font = await jimp.loadFont('./name.fnt'), 
mask = await jimp.read('https://i.imgur.com/552kzaW.png'), 
welcome = await jimp.read(randomkontol()),  
avatar = await jimp.read(await conn.profilePictureUrl(m.sender, 'image').catch(() => 'https://telegra.ph/file/24fa902ead26340f3df2c.png')), 
status = (await conn.fetchStatus(m.sender).catch(console.log) || {}).status?.slice(0, 30) || 'Not Detected' 
  
await avatar.resize(460, 460) 
await mask.resize(460, 460) 
fork icon0
star icon1
watch icon1

+ 39 other calls in file

10
11
12
13
14
15
16
17
18
19
if (ext !== '.png') {
    console.error(`Invalid file format. Expected .png, got ${ext}`);
    return;
}

const image = await Jimp.read(inputFile);
const width = image.bitmap.width;
const height = image.bitmap.height;
let minX = width;
let minY = height;
fork icon0
star icon1
watch icon0

60
61
62
63
64
65
66
67
68
69
const imageURl = image.data.data[0].url;

console.log(caption);
console.log(imageURl);

Jimp.read(imageURl).then((lenna) => {
    return lenna
    .resize(1024, 1024, Jimp.RESIZE_NEAREST_NEIGHBOR)
    .quality(100)
    .write("./image.jpeg")
fork icon0
star icon1
watch icon0