
前提
Windows 10 の Visual Studio 2022 で の.NET6のFrameworkでWindows Forms アプリです。
Form上に画像を一覧で表示するため下のコードによって行っている。
Pictureboxを使って、座標を指定していろんな画像を表示させたいのですが、
フォルダーのパスで読み込む画像を指定すると、
自分のパソコンでは動くけど、
作製したプロジェクトのフォルダーごと他人のパソコンで実行すると動かなくなったので、
何か良い方法はありませんか?
C#
1 /// <summary> 2 /// 画像を一覧で表示するために行っている 3 /// </summary> 4 public class Item 5 { 6 /// <summary> 7 /// ID 8 /// </summary> 9 public int id { get; set; } 10 11 /// <summary> 12 /// 商品の名前 13 /// </summary> 14 public string Name { get; set; } 15 16 /// <summary> 17 /// 画像 18 /// </summary> 19 public string Image { get; set; } 20 }
C#
1 public void imge() 2 { 3 ///画像のファイル名のリスト 4 List<Item> imagelist = new List<Item>(){ 5 new Item {id = 1, Name ="りんご", Image = "apple.jpg"}, 6 new Item {id = 2, Name ="ペン", Image = "seal.jpg" }, 7 new Item {id = 3, Name = "ぬいぐるみ", Image = "no_image.jpg"} 8 }; 9 10 //商品画像をセット 11 for (int i = 0; i < imagelist.Count; i++) 12 { 13 //商品情報のトップの位置 14 var locationY = 70; 15 //商品情報の配置の間隔 16 var location = i * 140; 17 18 var name = imagelist[i].Name; 19 20 //画像ファイルを読み込んで、Imageオブジェクトとして取得する 21 Image img = Image.FromFile(@"C:\test\" + imagelist[i].Image); 22 23 PictureBox pictureBox = new PictureBox() 24 { 25 Name = name, 26 Image = img, 27 Size = new Size(100, 100), 28 SizeMode = PictureBoxSizeMode.Zoom, 29 }; 30 pictureBox.Location = new Point(40, locationY + location); 31 Controls.Add(pictureBox); 32 }
実現したいこと
・必ず、
C#
1 ///画像のファイル名のリスト 2 List<Item> imagelist = new List<Item>(){ 3 new Item {id = 1, Name ="りんご", Image = "apple.jpg"}, 4 new Item {id = 2, Name ="ぬいぐるみ", Image = "seal.jpg" }, 5 new Item {id = 3, Name = "ペン", Image = "no_image.jpg"} 6 }; 7 8プロジェクト名のフォルダーだけを送るだけで実行する。
のImage = "apple.jpg"の部分を使って画面表示を行うことである。
発生している問題・エラーメッセージ
Image img = Image.FromFile(@"C:\test\" + imagelist[i].Image);
で例外が発生した。
エラーのメッセージの内容は
System.IO.FileNotFoundException
HResult=0x80070002
Message=C:\test\apple.jpg
Source=System.Drawing.Common
である。
調べたこと・実行したこと
1.サイトでアプリケーションのリソースとして画像を埋め込んで使用する方法があると書いていたが、
その方法がわからない。
2.原因が完全パスのやり方によって実行できないと考えたので、
画像ファイルのパスを相対パスで指定するように書く方法
「プロジェクト」のを右クリックして、
「新しいフォルダー」を追加し、名前はimageとする。
エクスプローラーから画像をドラッグ&ドロップで追加
画像ファイルのパスは相対パスで指定するように書く方法で行った。
C#
1//商品画像をセット 2 for (int i = 0; i < imagelist.Count; i++) 3 { 4 //商品情報のトップの位置 5 var locationY = 70; 6 //商品情報の配置の間隔 7 var location = i * 140; 8 9 var name = imagelist[i].Name; 10 11 //画像ファイルを読み込んで、Imageオブジェクトとして取得する 12 Image img = Image.FromFile(@".\image\" + imagelist[i].Image);//相対パスで指定するようにコードを書いた 13 14 PictureBox pictureBox = new PictureBox() 15 { 16 Name = name, 17 Image = img, 18 Size = new Size(100, 100), 19 SizeMode = PictureBoxSizeMode.Zoom, 20 }; 21 pictureBox.Location = new Point(40, locationY + location); 22 Controls.Add(pictureBox); 23 }
しかし、
System.IO.FileNotFoundException
HResult=0x80070002
Message=C:\Users\------\source\Visal\FreeTraining\FreeTraining\bin\Debug\net6.0-windows\image\apple.jpg
とエラーが発生してしまった。
その後もサイトで調べたことは2の書き方も1のアプリケーションのリソースについて関係がある書き方をしていた。



回答2件
あなたの回答
tips
プレビュー