コード例 #1
0
        /// <summary>
        /// 重新调整图片的尺寸
        /// </summary>
        /// <param name="imageStream">源图片流</param>
        /// <param name="maxSize">最大尺寸</param>
        /// <param name="isSameRate">是否保存相同比率</param>
        /// <returns></returns>
        public static byte[] Resize(Stream imageStream, ImageSize maxSize, bool isSameRate = false)
        {
            using (SKManagedStream managedStream = new SKManagedStream(imageStream)) //包装流
            {
                using (SKBitmap bitmap = SKBitmap.Decode(managedStream))             // 将流加载到图片中
                {
                    if (bitmap == null)
                    {
                        throw new ImageException("传递的参数不是有效图片");
                    }

                    ImageSize sourceSize = new ImageSize(bitmap.Width, bitmap.Height);
                    ImageSize newSize    = maxSize;
                    if (isSameRate)
                    {
                        newSize = ImageSize.GetSameRateSize(sourceSize, maxSize);
                    }

                    using (SKBitmap newBitmap = bitmap.Resize(new SKImageInfo(newSize.Width, newSize.Height), SKFilterQuality.High))
                    {
                        if (newBitmap == null)
                        {
                            throw new ImageException("调整图片尺寸失败");
                        }

                        using (SKImage image = SKImage.FromBitmap(newBitmap))
                        {
                            using (SKData p = image.Encode(SKEncodedImageFormat.Jpeg, 100))
                            {
                                return(p.ToArray());
                            }
                        }
                    }
                }
            }
        }