开发者

How to create a `pixelized' SVG image from a bitmap?

I have a 16x16 bitmap and want to create an SVG that contains 16x16 squares with the colors of the pixels of the image. Is there an easy way to achieve this?

My current thoughts go into the direction of using Python and PIL to read the bitmap image and dynamically create an SVG image file with the开发者_运维问答 corresponding objects. But this feels a little clumsy and like reinventing the wheel.

Is there a better way to do this?


If you don't need the output to be SVG, I would suggest using an HTML5 Canvas where you can sample the pixels of the image client-side (using getImageData() on the context) and then draw your own up-scaled image. Or, if you need SVG, you could still use Canvas for the image sampling and then use procedurally-created <rect/> elements in SVG for each pixel.

I've written an example using just HTML Canvas so you can see how to do this. In short:

function drawPixelated(img,context,zoom,x,y){
  if (!zoom) zoom=4; if (!x) x=0; if (!y) y=0;
  if (!img.id) img.id = "__img"+(drawPixelated.lastImageId++);
  var idata = drawPixelated.idataById[img.id];
  if (!idata){
    var ctx = document.createElement('canvas').getContext('2d');
    ctx.width  = img.width;
    ctx.height = img.height;
    ctx.drawImage(img,0,0);
    idata = drawPixelated.idataById[img.id] = ctx.getImageData(0,0,img.width,img.height).data;
  }
  for (var x2=0;x2<img.width;++x2){
    for (var y2=0;y2<img.height;++y2){
      var i=(y2*img.width+x2)*4;
      var r=idata[i  ];
      var g=idata[i+1];
      var b=idata[i+2];
      var a=idata[i+3];
      context.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
      context.fillRect(x+x2*zoom, y+y2*zoom, zoom, zoom);
    }
  }
};
drawPixelated.idataById={};
drawPixelated.lastImageId=0;

If you really need SVG involved, I'd be happy to write an example that dynamically generated that.

Edit: OK, I've created an SVG version just for fun and practice. :)

As an aside (from an initial misreading of your question) this demo file from ASVG3 their old SVG Examples Page shows how to use some complex compositing of many different effects to create pixelation on arbitrary vector data. Unfortunately the demo does not load in Chrome, having been hardwired to require the (now-discontinued) Adobe SVG Viewer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜