我試圖將原始圖像縮放爲50%和25%,並嘗試在MVC中下載縮放圖像。我正在使用從Google搜索中獲取的以下代碼。在縮放時獲取更大尺寸的圖像C#
public byte[] ScaleImageByPercent(byte[] imageBuffer, int Percent)
{
using (Stream imageStream = new MemoryStream(imageBuffer))
{
using (Image scaleImage = Image.FromStream(imageStream))
{
float scalePercent = ((float)Percent/100);
int originalWidth = scaleImage.Width;
int originalHeight = scaleImage.Height;
int originalXPoint = 0;
int originalYPoint = 0;
int scaleXPoint = 0;
int scaleYPoint = 0;
int scaleWidth = (int)(originalWidth * scalePercent);
int scaleHeight = (int)(originalHeight * scalePercent);
using (Bitmap scaleBitmapImage = new Bitmap(scaleWidth, scaleHeight, PixelFormat.Format24bppRgb))
{
scaleBitmapImage.SetResolution(scaleImage.HorizontalResolution, scaleImage.VerticalResolution);
Graphics graphicImage = Graphics.FromImage(scaleBitmapImage);
graphicImage.CompositingMode = CompositingMode.SourceCopy;
graphicImage.InterpolationMode = InterpolationMode.NearestNeighbor;
graphicImage.DrawImage(scaleImage,
new Rectangle(scaleXPoint, scaleYPoint, scaleWidth, scaleHeight),
new Rectangle(originalXPoint, originalYPoint, originalWidth, originalHeight),
GraphicsUnit.Pixel);
graphicImage.Dispose();
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(scaleBitmapImage, typeof(byte[]));
}
}
}
}
當我使用3.4MB的圖像返回4.7MB的50%,甚至100%的最差返回18 MB。
編輯: 獲取字節數組後,我使用下面的代碼下載圖像。下載後,我檢查磁盤中的文件大小,顯示更大的大小。
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(scaledBytes));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
我是否正確地進行縮放?哪一個我需要改變獲得較小的圖像,同時使用上述功能進行縮放。
你是比較兩個字節數組的大小還是磁盤上文件的大小?請記住,當你加載一個500Kb的JPG文件時,它會在內存中解壓縮,產生一個更大的字節數組(至少32bits *像素寬×像素高)。因此,您可以從一個非常小的JPG文件中獲得「幾兆字節」的字節數組(這可能是您在100%調整大小時看到的情況)。這將有效地匹配您的值:百分比50%=結果圖像是原始圖像的1/4,4.7Mb是18Mb的1/4。 –
@Leo。我正在比較磁盤上文件的大小。請參閱我的編輯。 – Ramesh
我爲你發佈了一個答案。正如我所說你的代碼完美地工作,這是一個圖像壓縮的問題。試試看,請讓我知道! –