位图交换实际图像的高度和宽度

问题描述 投票:0回答:1

当我将图像作为流放置到位图时出现问题。

代码交换图像的宽度和高度。图像的实际尺寸为:实际宽度:3216px实际高度:4288px

但是下面的代码将其交换,因此Height为3216px,Width为4288px保存位图时,图像也会旋转。

FileStream fs = new FileStream("C:/image.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Bitmap bitmap = new Bitmap(fs);
                                int width = bitmap.Width; int height = bitmap.Height; bool hasresized = false; 
                                double ratio = Convert.ToDouble(width) / Convert.ToDouble(height);
                                while (true)
                                {
                                    if (width <= 900 && height <= 675) { break; }
                                    height--;
                                    width = Convert.ToInt32(ratio * Convert.ToDouble(height));
                                }
                                if (width != bitmap.Width || height != bitmap.Height)
                                {
                                    //We need to resize
                                    bitmap = ResizeImage(bitmap, width, height); hasresized = true; 
                                }

                                SaveImage(bitmap, "test.jpg", ImageFormat.Jpeg, quality); 
                                fs.Close();                     


  public void SaveImage(Bitmap bitmap, String fileName, ImageFormat imageFormat, long quality = 100L)
        {
            using (var encoderParameters = new EncoderParameters(1))
            using (encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality))
            {
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

                bitmap.Save(fileName, codecs.Single(codec => codec.FormatID == imageFormat.Guid), encoderParameters);
            }
        }
        public Bitmap ResizeImage(Image image, int width, int height)
        {
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            }
            return destImage;
        }

这是保存时的图像。它已向右旋转90:enter image description here

c# bitmap height width
1个回答
-1
投票

您可以打印带有最终图像的屏幕截图吗?这张图片还真的是JPG吗?

© www.soinside.com 2019 - 2024. All rights reserved.