おもわずツッコンでしまった。反省はしていない。
やりたかったこと=「一辺が3000ピクセルとかでかいサイズの写真をちっちゃくしてやんよ!」
勉強がてら作ってみるぜ!ってことで、VisualSudio2008で作ってみたサンプル。
画面こんな感じ。InとOut用のファイルダイアログと、ボタン2つとピクチャボックス
Public Class Form1
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
'読み込みボタン処理
Dim myFile As String
'マイドキュメントをみてやんよ!
openDialog.InitialDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If openDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
'ファイルとってきたら、イメージ変換だぜ!
myFile = openDialog.FileName
'オリジナルのサイズで読み込み
Dim orgImage As Image = Image.FromFile(myFile)
Dim newBitmap As New Bitmap(orgImage)
'ちっちゃくするサイズ決定(今回は横200px固定)
Dim setW As Integer = 200
Dim setH As Integer = Int(newBitmap.Height * (setW / newBitmap.Width))
'ちっちゃくするイメージ準備
Dim convBitmap As New Bitmap(setW, setH)
Dim convGraphics = Graphics.FromImage(convBitmap)
convGraphics.DrawImage(orgImage, New Rectangle(0, 0, setW, setH))
'ちっちゃくできたら、オリジナルはサヨウナラ
orgImage.Dispose()
'画面にサンプルイメージ表示
convPicture.Width = setW
convPicture.Height = setH
convPicture.SizeMode = PictureBoxSizeMode.StretchImage
convPicture.Image = convBitmap
convPicture.Tag = IO.Path.GetExtension(myFile)
End If
End Sub
Private Sub btnDo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDo.Click
'ほぞん処理
'マイドキュメントにいれてやんよ!
SaveDialog.InitialDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
SaveDialog.Filter = String.Format("(*{0})|*{0}", convPicture.Tag)
SaveDialog.DefaultExt = convPicture.Tag
If SaveDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
'JPGとBMPでいれちゃうよー
If convPicture.Tag.ToString.ToLower = ".jpg" Then
convPicture.Image.Save(SaveDialog.FileName, Imaging.ImageFormat.Jpeg)
ElseIf convPicture.Tag.ToString.ToLower = ".bmp" Then
convPicture.Image.Save(SaveDialog.FileName, Imaging.ImageFormat.Bmp)
End If
End If
End Sub
End Class
ソースはこれで全部。
「よみこみ」ボタン押して「ほぞん」ボタン押すだけの簡単なお仕事。
でも、ここに至るまでが大変だったの。
- 行32~33にDisposeを入れて使ったImageクラスは破棄、
- PictureBoxコントロールへFromFileで処理していた部分をBitmapクラスから読み込むように変更
をしておかないと、
「GDI+ で汎用エラーが発生しました。」なんて言われて、行61~69のSave処理で叱られまする。
(ほかにも色々といじったような気もするけど<おい。とにかく、このソースでは出なくなったのでw)
Image.FromFile メソッド (String, Boolean) (System.Drawing)
http://msdn.microsoft.com/ja-jp/library/4sahykhd(vs.80).aspx
↑ なんとなく気になった記述。原因となったのかどうかは判んないけど。確かに、これの対処したら、出なくなった。