最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - split base64 image into parts - Stack Overflow

matteradmin2PV0评论

I am trying to split an image file with javascript or jquery into four equal parts. Is it possible to split image like 280px x 60px into four equal parts, and save them encoded with base64 into four variables?

I am trying to split an image file with javascript or jquery into four equal parts. Is it possible to split image like 280px x 60px into four equal parts, and save them encoded with base64 into four variables?

Share Improve this question asked Aug 23, 2014 at 15:19 Иван ЗахариевИван Захариев 1331 gold badge2 silver badges5 bronze badges 1
  • 2 You can calculate the image area needed for 4 canvas elements. Create in-memory your 4 canvases, place and reposition your images and simply get the resulting base64 encoded strings. – Roko C. Buljan Commented Aug 23, 2014 at 15:21
Add a ment  | 

1 Answer 1

Reset to default 9

Let's say we have a Base64 image like:

Let's go get those 4 images!


  1. Create an in-memory canvas element and prepare it's context:

var canvas = document.createElement('canvas');
var ctx    = canvas.getContext("2d");

  1. Than let's prepare an empty Array to later store our base64 strings:

var parts = [];

  1. Now we need to create a new Image, assign an onload function and set it's src:

var img = new Image();
img.onload = split_4;
img.src = "data:image/png;base64,iVBORw0KGgoAAAA.......................etc"

  1. The split_4 function:

If the image we need to slice is 260×80 means that we need to set our canvas element to 1/4 that size:

var w2 = img.width  / 2,  // 130
    h2 = img.height / 2;  // 40

canvas.width  = w2;
canvas.height = h2;   

  1. Paint our canvas 4 times, each time moving our image to new XY positions:

//      0   0    1.iteration
//   -130   0    2.iteration
//      0 -40    3.iteration
//   -130 -40    4.iteration

and on each loop iteration we simply push the retrieved Canvas data into our parts Array:

for(var i=0; i<4; i++){

  var x = (-w2*i) % (w2*2),              // New X position
      y = (h2*i)<=h2? 0 : -h2 ;          // New Y position

  ctx.drawImage(this, x, y, w2*2, h2*2); // imgObject, X, Y, width, height
  parts.push( canvas.toDataURL() );      // ("image/jpeg") for jpeg

}

Now always inside the onload function you can retrieve all your image parts from array:

console.log( parts ); //  ["data:image/png;base64,iV...z9d/oBHAAAAAElFTkSuQmCC",
                      //   "data:image/png;base64,iV...yVhNNW1AAAAAElFTkSuQmCC", 
                      //   "data:image/png;base64,iV...Q2FoAAAAABJRU5ErkJggg==", 
                      //   "data:image/png;base64,iV...RQXgXQAAAAASUVORK5CYII="]

To get only (i.e.) the first image use: parts[0];


Example:

var canvas = document.createElement('canvas'), // In memory canvas
    ctx = canvas.getContext("2d"),
    parts = [], // to push into oud base64 strings
    img = new Image();

function split_4() {

  var w2 = img.width  / 2,
      h2 = img.height / 2;

  for (var i = 0; i < 4; i++) {

    var x = (-w2 * i) % (w2 * 2),
      y = (h2 * i) <= h2 ? 0 : -h2;

    canvas.width = w2;
    canvas.height = h2;

    ctx.drawImage(this, x, y, w2 * 2, h2 * 2); // img, x, y, w, h
    parts.push(canvas.toDataURL()); // ("image/jpeg") for jpeg

    //>> JUST FOR DEMO
    var slicedImage = document.createElement("img")
    slicedImage.src = parts[i];
    var div = document.getElementById("test");
    div.appendChild(slicedImage);
    //<< JUST FOR DEMO
  }
  console.log(parts);
};

img.onload = split_4;
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQQAAABQCAYAAAD/YAtfAAAD6klEQVR4nO3c6Y0jIRCGYWdCKIRCKIRCKIRCKLU/dlxdzdDQF7ZHfkt6pB3uktbfzmqPhzxEAEAeIo93PwDA5yAQACgCAYAiEAAoAgGAIhAAKAIBgCIQACgCAYAiEAAoAgGAIhAAKAIBgCIQACgCAYAiEAAoAgGAIhAAKAIBgCIQACgCAYAiEAAoAgGAIhAAKAIBgCIQACgCAYAiEAAoAgGAIhAAKAJhJiciSUSK/K8iIuHA/vRzxrv7OMOLSJal8s/Yu9+FLgJhFidLENSVduxPZn0YrI2y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";
img {
  margin: 10px;
}
<div id="test"></div>

Post a comment

comment list (0)

  1. No comments so far