0

「すべての画像形式を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
4

1 に答える 1