我正在寻找“将所有图像格式转换为 JPG”的解决方案。
我当前的代码:
public ActionResult UploadProfilFotografi(HttpPostedFileBase file)
{
int sessionUID = int.Parse(Session["UID"].ToString());
using (var dbContext = new DB_EMafya())
{
if (file != null
&& file.ContentLength > 1
&& file.ContentLength < 5120
&& myFunction.IsImage(file))
{
var users = dbContext
.tbl_Users
.FirstOrDefault(a => a.UID == sessionUID);
if (users != null)
{
string newPicName = (string) Session["UID"];
string extension = Path.GetExtension(file.FileName);
if (extension != null)
{
string picext = extension.ToLower();
string originalpath = Path.Combine(
Server.MapPath("~/up/profile-pictures/originals"),
newPicName + picext);
// file is uploaded
file.SaveAs(originalpath);
}
}
}
}
return RedirectToAction("ProfilAyarlari", "Profil");
}
你能帮忙吗?
我找到了一个解决方案: c#将图像格式转换为jpg
我编辑了一些并添加了更多的值来运行。并把代码放进去使用。
private void SaveAsJpgWithVaryQualityLevel(HttpPostedFileBase file, string toPath, string fileName)
{
using (var target = new MemoryStream())
{
file.InputStream.CopyTo(target);
using (var bmp1 = new Bitmap(target)) // Get a bitmap.
{
var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
var myEncoder = Encoder.Quality;
using (var myEncoderParameters = new EncoderParameters(1))
{
using (var myEncoderParameter = new EncoderParameter(myEncoder, 100L))
{
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(@"" + toPath + fileName, jgpEncoder, myEncoderParameters);
}
}
}
}
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
}
来电:
string newPicName = Convert.ToString(Session["UID"]) + ".jpg";
string toPath = Server.MapPath("~/_up/profile-pictures/originals/");
SaveAsJpgWithVaryQualityLevel(file, toPath, newPicName); // file is uploaded