【问题标题】:Can't consume byte[] or stream from WCF to create an image无法使用 byte[] 或来自 WCF 的流来创建图像
【发布时间】:2013-11-04 19:53:09
【问题描述】:

更新:知道了!答案贴在下面...我会清理这个问题,以便对其他人更有用。

我有一项服务,它使用一个库来使用 WebBrowser 控件从 html 页面生成缩略图。这很好,但我需要创建一个 WCF 服务,允许您传入一个 uri,然后该服务将其转换为缩略图并返回它。我已经将它作为 Stream 和 byte[] 进行了尝试。它在服务中创建图像,我将其保存为文件只是为了证明它,但是当我使用它时,我会获取数据(超过我发送的数据)并且我无法将其保存为可视图像。任何建议,将不胜感激。我不是 WCF 专家,所以我希望我错过了一些容易发现的东西。

这是服务,它托管在控制台应用程序中,并包含 Main() 过程。

namespace RawImageService
{
    [ServiceContract]
    public interface IImageServer
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/image/?uri={uri}")]
        Stream HtmlToImage(string uri);
   }

     public class Service : IImageServer
    {
        public Stream HtmlToImage(string uri)
        {
            string path = @"D:\Templates\HtmlServiceImage.bmp";

            if( File.Exists(path) )
                File.Delete(path);

            if (string.IsNullOrEmpty(uri))
            {
                return null;
            }
            else
            {
                if ((uri.IndexOf("file:", System.StringComparison.Ordinal) < 0) &&
                    (uri.IndexOf("http", System.StringComparison.Ordinal) < 0))
                    uri = "http://" + uri;

                Thumbnail.Uri = uri;
                try
                {
                    Bitmap bitmap =
                        HtmlToThumbnail.WebsiteThumbnail.GetThumbnail(Thumbnail.Uri, Thumbnail.Width,
                                                                      Thumbnail.Hight, Thumbnail.ThumbWidth,
                                                                      Thumbnail.ThumbHight);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, ImageFormat.Jpeg);
                        bitmap.Save(path, ImageFormat.Jpeg);

                        ms.Position = 0;

                        WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

                    return ms;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return null;
            }
        }

        static void Main(string[] args)
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(IImageServer), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
            host.Open();
            Console.WriteLine("Service is running");
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();

        }
     }
  } 

这是我使用服务的尝试:

private static void Main(string[] args)
{
    string uri = string.Concat("http://localhost:8000",
                   string.Format("/image/?uri={0}", "file:///D:/Templates/Test4.htm"));

    tryThis(uri);
}

public static void tryThis(string uri)
{
    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
    request.Method = "GET";

    // Get response   
    using (WebResponse response = request.GetResponse() as WebResponse)
    {
        using (Stream stream = response.GetResponseStream())
        {
            byte[] buffer = new byte[response.ContentLength];
            MemoryStream ms = new MemoryStream();
            int bytesRead, totalBytesRead = 0;

            do
            {
                bytesRead = stream.Read(buffer, 0, buffer.Length);
                totalBytesRead += bytesRead;

                ms.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);

            string path = @"D:/templates/fs.jpg";
            if (File.Exists(path))
                File.Delete(path);

            var fs = new FileStream(path, FileMode.Create);
            fs.Write(ms.ToArray(), 0, totalBytesRead);
            fs.Flush();
            fs.Close();
        }
    }
}

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

.config 文件中没有任何其他内容。我将开始研究这一点,但我的理解是我可以在应用程序本身中配置所有内容。

我不在乎我用哪种方式让它工作,我只需要让它工作。我很感激任何建议。谢谢。

【问题讨论】:

    标签: c# .net wcf steam


    【解决方案1】:

    我得到了 Stream 方法。这是代码。我可以这样访问它:

    http://localhost:8000/image/?uri=file:///D:/Templates/Test4.htm
    

    这是新方法。如果你用它替换上面的代码,它就可以工作。

    public Stream HtmlToImage(string uri)
    {
        string path = @"D:\Templates\HtmlServiceImage.bmp";
    
        if( File.Exists(path) )
            File.Delete(path);
    
        if (string.IsNullOrEmpty(uri))
        {
            return null;
        }
        else
        {
            if ((uri.IndexOf("file:", System.StringComparison.Ordinal) < 0) &&
                (uri.IndexOf("http", System.StringComparison.Ordinal) < 0))
                uri = "http://" + uri;
    
            Thumbnail.Uri = uri;
            try
            {
                Bitmap bitmap =
                    HtmlToThumbnail.WebsiteThumbnail.GetThumbnail(Thumbnail.Uri, Thumbnail.Width,
                                                                  Thumbnail.Hight, Thumbnail.ThumbWidth,
                                                                  Thumbnail.ThumbHight);
                MemoryStream ms = new MemoryStream();
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Position = 0;
                WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
                return ms;
            }
            catch (Exception)
            {
                throw;
            }
            return null;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2017-01-22
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多