开发者

Algorithm help for image generation on the fly

I wish to create a helper for generation of images. We're going to add it to a C# solution. However, I'm not the backend developer so I'll just create a dummy example and explain in my own words here :-)

Update: What I need help for, is how to calculate the scaling for each of the scenarios below. E.g. if I have a 60x60 thumbnail placeholder, and the original image is 400x300, I'd have to set 300 to 60 and change the 400 accordingly.

The helper would look something like this:

HelperName('OriginalImageUrl', 'FileName', X, Y, M)

M is Mode, which I guess is needed to decide if it should use width or height to calculate from.. These are the scenarios:

Thumnails (square): width and height is the same, so it should probably use the shortest image dimension.

ImagePlaceholder (mostly rectangular): static height/width. The image needs to fill both height/width so there wont be any blank areas in the placeholder. What's excessive in one of the dimensions will be cropped. Could probably be combined with the Thumbnail one just with checks on the dimensions if the width != height to determine if its a square or not.

PhotoWrapper: ma开发者_StackOverflowx height/width. The entire image will be adjusted to fit within these proportions. No cropping, just basic resize to fit within 2 given container dimensions.

If someone could help me with this, or know a plugin what I could use, it'd be awesome.


You can calculate the scaling factor, and then the input/output rectangles. Should be something like this(didn't test it):

Fitting:

double scaleX=(double)targetWidth/(double)originalWidth;
double scaleY=(double)targetHeight/(double)originalHeight; 

double scaleToFit=Math.Min(scaleX,scaleY);

double newWidth=scaleToFit*originalWidth;
double newHeight=scaleToFit*originalHeight;

double borderX=(targetWidth-newWidth)/2;
double borderY=(targetHeight-newHeight)/2;

Rect InputRect=new Rect(0,0,originalWidth,originalHeight);
Rect OutputRect=new Rect(borderX,borderY,targetWidth-2*borderX,targetHeight-2*borderY);

Filling:

double scaleX=(double)targetWidth/(double)originalWidth;
double scaleY=(double)targetHeight/(double)originalHeight; 

double scaleToFill=Math.Max(scaleX,scaleY);

double oldWidth=targetWidth/scaleToFill;
double oldHeight=targetHeight/scaleToFill;

double cropX=(originalWidth-oldWidth)/2;
double cropY=(originalHeight-oldHeight)/2;

Rect OutputRect=new Rect(0,0,targetWidth,targetHeight);
Rect InputRect=new Rect(cropX,cropY,oldWidth,oldHeight);

I think there are blitting functions which take an two images, and two rectangles. Use one of those.


  1. Load the image from the URL into a byte[]
  2. Create an Image from the byte[]
  3. Manipulate Image
  4. Save Image to disk and serve URL or stream directly via a web handler

byte[] can be replaced by Stream.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜