2010-05-11 50 views
83

Tôi muốn hiển thị hình ảnh thu nhỏ trong chế độ xem lưới từ vị trí tệp. Cách tạo tệp .jpeg? Tôi đang sử dụng ngôn ngữ C# với asp.net.Tạo hình thu nhỏ

+5

[ImageResizer] (http://imageresizing.net) là thư viện an toàn cho máy chủ được thiết kế để thực hiện chính xác những gì bạn cần. Không giống như GetThumbnailImage, nó tạo ra kết quả chất lượng cao, và không giống như các mẫu mã, nó không bị rò rỉ bộ nhớ như một cái rây. Bạn có thể không quan tâm bây giờ, nhưng bạn sẽ trong một vài tháng khi bạn đang đầu gối sâu trong bãi lõi. –

+1

http://www.codeproject.com/Articles/20971/Thumbnail-Images-in-GridView-using-C – Freelancer

Trả lời

198

Bạn phải sử dụng phương pháp GetThumbnailImage trong lớp Image:

https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx

Dưới đây là một ví dụ thô mà phải mất một tập tin hình ảnh và tạo ra một hình ảnh thu nhỏ từ nó, sau đó lưu nó lại vào đĩa.

Image image = Image.FromFile(fileName); 
Image thumb = image.GetThumbnailImage(120, 120,()=>false, IntPtr.Zero); 
thumb.Save(Path.ChangeExtension(fileName, "thumb")); 
+3

@ktsixit - Đó là trong không gian tên System.Drawing (trong System.Drawing.dll) –

+12

Bạn có nghiêm túc không? GetThumbnailImage tạo ra kết quả khủng khiếp trên hình ảnh đã nhúng hình thu nhỏ rồi. [Dont 'làm cho những sai lầm] (http://nathanaeljones.com/163/20-image-resizing-pitfalls/), xin vui lòng. http://imageresizing.net là nguồn mở, miễn phí, nhanh chóng và sẽ cung cấp cho bạn kết quả chất lượng cao. –

+3

Nó chỉ có thể được sử dụng trên hình ảnh JPG nói chung. Nếu bạn cố gắng thay đổi kích thước hình ảnh PNG như thế này, bạn sẽ gặp phải lỗi này. – HBlackorby

22

Các mã sau đây sẽ viết một hình ảnh trong tỉ lệ với phản ứng, bạn có thể sửa đổi mã cho mục đích của bạn:

public void WriteImage(string path, int width, int height) 
{ 
    Bitmap srcBmp = new Bitmap(path); 
    float ratio = srcBmp.Width/srcBmp.Height; 
    SizeF newSize = new SizeF(width, height * ratio); 
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height); 
    HttpContext.Response.Clear(); 
    HttpContext.Response.ContentType = "image/jpeg"; 
    using (Graphics graphics = Graphics.FromImage(target)) 
    { 
     graphics.CompositingQuality = CompositingQuality.HighSpeed; 
     graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 
     graphics.CompositingMode = CompositingMode.SourceCopy; 
     graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height); 
     using (MemoryStream memoryStream = new MemoryStream()) 
     { 
      target.Save(memoryStream, ImageFormat.Jpeg); 
      memoryStream.WriteTo(HttpContext.Response.OutputStream); 
     } 
    } 
    Response.End(); 
} 
+0

Tôi đã cung cấp đường dẫn tệp cục bộ của mình trong đường dẫn chuỗi. nó trả về "định dạng đường dẫn nhất định không được hỗ trợ". –

+0

tôi đã cho như thế này ... var path = @ "C: \ Users \ Gopal \ Desktop \ files.jpeg"; Bitmap srcBmp = Bitmap mới (đường dẫn); –

0

Dưới đây là một ví dụ đầy đủ về cách để tạo ra một hình ảnh nhỏ hơn (thumbnail). Đoạn mã này thay đổi kích thước hình ảnh, xoay nó khi cần thiết (nếu điện thoại được giữ theo chiều dọc) và đánh dấu hình ảnh nếu bạn muốn tạo ngón tay cái vuông. Đoạn mã này tạo ra một JPEG, nhưng nó có thể dễ dàng được sửa đổi cho các loại tệp khác. Ngay cả khi hình ảnh sẽ nhỏ hơn kích thước tối đa cho phép, hình ảnh sẽ vẫn được nén và độ phân giải của nó bị thay đổi để tạo ra hình ảnh có cùng mức độ nén và dpi.

using System; 
using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Drawing.Imaging; 
using System.IO; 

//set the resolution, 72 is usually good enough for displaying images on monitors 
float imageResolution = 72; 

//set the compression level. higher compression = better quality = bigger images 
long compressionLevel = 80L; 


public Image resizeImage(Image image, int maxWidth, int maxHeight, bool padImage) 
{ 
    int newWidth; 
    int newHeight; 

    //first we check if the image needs rotating (eg phone held vertical when taking a picture for example) 
    foreach (var prop in image.PropertyItems) 
    { 
     if (prop.Id == 0x0112) 
     { 
      int orientationValue = image.GetPropertyItem(prop.Id).Value[0]; 
      RotateFlipType rotateFlipType = getRotateFlipType(orientationValue); 
      image.RotateFlip(rotateFlipType); 
      break; 
     } 
    } 

    //apply the padding to make a square image 
    if (padImage == true) 
    { 
     image = applyPaddingToImage(image, Color.Red); 
    } 

    //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions 
    if (image.Width > maxWidth || image.Height > maxHeight) 
    { 
     double ratioX = (double)maxWidth/image.Width; 
     double ratioY = (double)maxHeight/image.Height; 
     double ratio = Math.Min(ratioX, ratioY); 

     newWidth = (int)(image.Width * ratio); 
     newHeight = (int)(image.Height * ratio); 
    } 
    else 
    { 
     newWidth = image.Width; 
     newHeight = image.Height; 
    } 

    //start the resize with a new image 
    Bitmap newImage = new Bitmap(newWidth, newHeight); 

    //set the new resolution 
    newImage.SetResolution(imageResolution, imageResolution); 

    //start the resizing 
    using (var graphics = Graphics.FromImage(newImage)) 
    { 
     //set some encoding specs 
     graphics.CompositingMode = CompositingMode.SourceCopy; 
     graphics.CompositingQuality = CompositingQuality.HighQuality; 
     graphics.SmoothingMode = SmoothingMode.HighQuality; 
     graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 
     graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; 

     graphics.DrawImage(image, 0, 0, newWidth, newHeight); 
    } 

    //save the image to a memorystream to apply the compression level 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     EncoderParameters encoderParameters = new EncoderParameters(1); 
     encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compressionLevel); 

     newImage.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters); 

     //save the image as byte array here if you want the return type to be a Byte Array instead of Image 
     //byte[] imageAsByteArray = ms.ToArray(); 
    } 

    //return the image 
    return newImage; 
} 


//=== image padding 
public Image applyPaddingToImage(Image image, Color backColor) 
{ 
    //get the maximum size of the image dimensions 
    int maxSize = Math.Max(image.Height, image.Width); 
    Size squareSize = new Size(maxSize, maxSize); 

    //create a new square image 
    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height); 

    using (Graphics graphics = Graphics.FromImage(squareImage)) 
    { 
     //fill the new square with a color 
     graphics.FillRectangle(new SolidBrush(backColor), 0, 0, squareSize.Width, squareSize.Height); 

     //put the original image on top of the new square 
     graphics.DrawImage(image, (squareSize.Width/2) - (image.Width/2), (squareSize.Height/2) - (image.Height/2), image.Width, image.Height); 
    } 

    //return the image 
    return squareImage; 
} 


//=== get encoder info 
private ImageCodecInfo getEncoderInfo(string mimeType) 
{ 
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); 

    for (int j = 0; j < encoders.Length; ++j) 
    { 
     if (encoders[j].MimeType.ToLower() == mimeType.ToLower()) 
     { 
      return encoders[j]; 
     } 
    } 

    return null; 
} 


//=== determine image rotation 
private RotateFlipType getRotateFlipType(int rotateValue) 
{ 
    RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone; 

    switch (rotateValue) 
    { 
     case 1: 
      flipType = RotateFlipType.RotateNoneFlipNone; 
      break; 
     case 2: 
      flipType = RotateFlipType.RotateNoneFlipX; 
      break; 
     case 3: 
      flipType = RotateFlipType.Rotate180FlipNone; 
      break; 
     case 4: 
      flipType = RotateFlipType.Rotate180FlipX; 
      break; 
     case 5: 
      flipType = RotateFlipType.Rotate90FlipX; 
      break; 
     case 6: 
      flipType = RotateFlipType.Rotate90FlipNone; 
      break; 
     case 7: 
      flipType = RotateFlipType.Rotate270FlipX; 
      break; 
     case 8: 
      flipType = RotateFlipType.Rotate270FlipNone; 
      break; 
     default: 
      flipType = RotateFlipType.RotateNoneFlipNone; 
      break; 
    } 

    return flipType; 
} 


//== convert image to base64 
public string convertImageToBase64(Image image) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     //convert the image to byte array 
     image.Save(ms, ImageFormat.Jpeg); 
     byte[] bin = ms.ToArray(); 

     //convert byte array to base64 string 
     return Convert.ToBase64String(bin); 
    } 
} 

Đối với người dùng asp.net một ví dụ nhỏ về cách tải lên tệp, thay đổi kích thước và hiển thị kết quả trên trang.

//== the button click method 
protected void Button1_Click(object sender, EventArgs e) 
{ 
    //check if there is an actual file being uploaded 
    if (FileUpload1.HasFile == false) 
    { 
     return; 
    } 

    using (Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream)) 
    { 
     try 
     { 
      //start the resize 
      Image image = resizeImage(bitmap, 256, 256, true); 

      //to visualize the result, display as base64 image 
      Label1.Text = "<img src=\"data:image/jpg;base64," + convertImageToBase64(image) + "\">"; 

      //save your image to file sytem, database etc here 
     } 
     catch (Exception ex) 
     { 
      Label1.Text = "Oops! There was an error when resizing the Image.<br>Error: " + ex.Message; 
     } 
    } 
} 
Các vấn đề liên quan