Create PNG image with C# HttpHandler webservice

后端 未结 6 623
我在风中等你
我在风中等你 2020-12-05 11:46

I\'d like to be able to create a simple PNG image, say of a red square using a c# web based service to generate the image, called from an

6条回答
  •  無奈伤痛
    2020-12-05 12:21

    There is another way to accomplish serving a dynamic image.

    namespace MyApp
    {
        [ServiceContract]
        public interface IMyService
        {
            [WebGet(UriTemplate = "Image.png")]
            [OperationContract]
            Stream ShowImage();
        }
    }
    

    For the implementation:

    public Stream ShowImage()
    {
        Bitmap image = new Bitmap(@"C:\Image.png");
        Image image2 = new Bitmap(125, 125);
    
        using (Graphics graphics = Graphics.FromImage(image2))
        {
               graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
               graphics.SmoothingMode = SmoothingMode.HighQuality;
               graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
               graphics.CompositingQuality = CompositingQuality.HighQuality;
               graphics.DrawImage(image, 0, 0, 125, 125);
        }
    
        MemoryStream imageAsMemoryStream = new MemoryStream();
        image2.Save(imageAsMemoryStream, ImageFormat.Png);
        imageAsMemoryStream.Position = 0;
        return imageAsMemoryStream;
    }
    

    Start the service as a regular WCF service and add the service in your app.config

    (WebService = new WebServiceHost(typeof(MyService))).Open();
    

    You can pass parameters to make it more dynamic.

提交回复
热议问题