簡體   English   中英

將 bitmap 保存在與原始名稱相同的文件夾中

[英]Save a bitmap at same folder as the original with a set name

我想制作一個程序,通過在控制台中輸入加載文件,將圖片轉換為灰度、負片和模糊。 然后我想在與原始文件相同的文件夾中復制轉換后的圖片,並在文件名中添加額外的文本(例如:picture_negative.jpg)。 我的問題是我無法弄清楚如何將圖片與額外的文本一起保存在保存文件夾中。

這是我編程的第一個月,所以我不是很有經驗。

static void Main(string[] args)
        {
            Bitmap picture;
            try
            {
                Console.Write("Write the file you want to edit ");
                picture = new Bitmap(Console.ReadLine=                 
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("No picture choosen");
                return;
            }
            catch (ArgumentException)
            {
                Console.WriteLine("error");
                return;
            }

            ConvertAlgoritms.ConvertAlgoritms.MakePictureGreyScale(picture);
            ConvertAlgoritms.ConvertAlgoritms.MakePictureNegative(picture);
            ConvertAlgoritms.ConvertAlgoritms.MakePictureBlurred(picture);
        }

class 示例

 public class ConvertAlgoritms
    {
        public static Bitmap MakePictureGreyScale(Bitmap originalPicture)
        {
            Bitmap newPicture = new Bitmap(originalPicture);

            int x, y;
            for (x = 0; x < newPicture.Width; x++)
            {
                for (y = 0; y < newPicture.Height; y++)
                {
                    Color pixel = newPicture.GetPixel(x, y);
                    int r = pixel.R;
                    int g = pixel.G;
                    int b = pixel.B;
                    int greyScale = (r + g + b) / 3;
                    newPicture.SetPixel(x, y, Color.FromArgb(greyScale, greyScale, greyScale));
                }
            }
            return newPicture;
        }
}

你有Bitmap.Save()

首先,您必須將控制台中輸入的文件名保存到變量中。

然后,你可以在 append 一個字符串到這個名字前擴展。

例子:

Console.Write("Write the file you want to edit ");
Filename = Console.ReadLine();
picture = new Bitmap(Filename);

string NewFilename = Path.GetFileNameWithoutExtension(Filename)
                   + StrToAppend
                   + Path.GetExtension(Filename);

picture.Save(Newfilename, picture.RawFormat);

您需要拿起返回的圖像,例如:

var greyscalePicture = ConvertAlgoritms.ConvertAlgoritms.MakePictureGreyScale(picture);

然后你可以保存它:

greyscalePicture.Save("Fancynewfilename.jpg", ImageFormat.Jpeg);

這假定您的文件格式是 JPEG。 要生成新文件名,您需要保留對舊文件名的引用。

var originalFilename = Console.ReadLine();
var picture = new Bitmap(originalFilename);

然后,您可以按照@Corak 的建議使用Path class 構建文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM