.net取得图片的大小代码

作者:袖梨 2022-06-25

.

internal static void RegisterPNGImage(string name, Uri uri)
        {
            StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
            if (resourceInfo != null && resourceInfo.Stream != null)
            {
                BitmapImage image = new BitmapImage();
#if SILVERLIGHT
                image.SetSource(resourceInfo.Stream);
#else
                image.BeginInit();
                image.StreamSource = resourceInfo.Stream;
                image.EndInit();
#endif
                resourceInfo.Stream.Position = 0;
                byte[] header = new byte[8];
                resourceInfo.Stream.Read(header, 0, header.Length);
                if (header[0] == 0x89 &&
                    header[1] == 0x50 && // P
                    header[2] == 0x4E && // N
                    header[3] == 0x47 && // G
                    header[4] == 0x0D && // CR
                    header[5] == 0x0A && // LF
                    header[6] == 0x1A && // EOF
                    header[7] == 0x0A)   // LF
                {
                    byte[] buffer = new byte[16];
                    resourceInfo.Stream.Read(buffer, 0, buffer.Length);
                    Array.Reverse(buffer, 8, 4);
                    Array.Reverse(buffer, 12, 4);

                    double width = BitConverter.ToInt32(buffer, 8);
                    double height = BitConverter.ToInt32(buffer, 12);

                    resourceInfo.Stream.Close();
                    ImageUtils.RegisterImageAsset(name, new ImageAsset(image, width, height));

                    return;
                }
                resourceInfo.Stream.Close();
            }
            new Exception("Can not load PNG Image '" + name + "' URI: " + uri);
        }

在此我替微软向去年当TWaver .NET还在beta中就已经开始在项目中预言和使用客户道歉,我们没有彻底做到DRY,不过始终坚持最大程序减少用户工作量原则的TWaver开发团队,在正式TWaver .NET 1.0发布时提供了让人更舒心的RegisterPNGImage(string name, Uri uri)函数,是的,你不用在告诉TWaver宽高了,TWaver会自动的去获取,至于如何获取很多同学很感兴趣,以下实现代码原理很简单我就不解释了,总之条条道路通罗马,Silverlight不提供的我们也能走出自己的路

相关文章

精彩推荐