locked
RichTextBox Images Quality Loss RRS feed

  • Question

  • Hi there!

    After i ever used the method to use the clipboard to insert images in to richtextbox. I see that when resizing the image, it get a very messed up color and quality. I was reseaching this and there is two ways as i saw. Using the Clipboard or using OLE objects. But these makes the color messed up, because its not real rtf code. The image has just been pasted right in, its not real rtf image code. There was a guy that found annother way to insert images that i think was called stdpicast. I got an pdf where he demonstrate how this is working and an zip file with the source project. The problem is that the project is in VB 6 format. Anyway, someone know how to insert images in this way or can convert the code in the zip of some kind?

    Thank you!

    PDF: Direct Download

    ZIP: Direct Download

    Tuesday, January 7, 2014 3:38 PM

Answers

  • Hello Everyone,

     This is an example i made of creating a Metafile from an image on your hard drive and pasting it into a RichTextBox. This method will produce a much better quality image than just pasting a standard bitmap image into your RichTextBox. You can re-size the image to the size of a postal stamp or to the size of the whole RichTextBox without  making your image look blurry and discolored. I commented the AddImageToRtb sub that i wrote so it should be fairly easy for anyone to understand the steps i took to do this. I don`t claim this to be a prize winning masterpiece but, it works pretty good.

     I also want to say Thanks Again to JohnWein for helping point me in the rite direction for doing this and for the helpful link he provided to the ClipboardMetafileHelper code which contains the PutEnhMetafileOnClipboard function i used in this example.

     You can test this example by creating a new Windows Form Application project and placing 2 Buttons and 1 RichTextBox onto the Form. Button1 will allow you to select an image from your hard drive to add to the RichTextBox. Button2 will allow you to save your Rich Text File to your hard drive. Have Fun!!!

    Imports System.Drawing.Imaging
    Imports System.Runtime.InteropServices
    
    Public Class Form1
        <DllImport("user32.dll", EntryPoint:="OpenClipboard")> Private Shared Function OpenClipboard(ByVal hWnd As IntPtr) As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="EmptyClipboard")> Private Shared Function EmptyClipboard() As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="SetClipboardData")> Private Shared Function SetClipboardData(ByVal uFormat As Integer, ByVal hWnd As IntPtr) As IntPtr
        End Function
        <DllImport("user32.dll", EntryPoint:="CloseClipboard")> Private Shared Function CloseClipboard() As Boolean
        End Function
        <DllImport("gdi32.dll", EntryPoint:="CopyEnhMetaFileA")> Private Shared Function CopyEnhMetaFile(ByVal hemfSrc As IntPtr, ByVal hNULL As IntPtr) As IntPtr
        End Function
        <DllImport("gdi32.dll", EntryPoint:="DeleteEnhMetaFile")> Private Shared Function DeleteEnhMetaFile(ByVal hemfSrc As IntPtr) As Boolean
        End Function
    
        'I do not claim to have written the PutEnhMetafileOnClipboard function.
        'For more information on this function and why it is needed refer to http://support.microsoft.com/kb/323530/en-us
        Private Shared Function PutEnhMetafileOnClipboard(ByVal hWnd As IntPtr, ByVal mf As Metafile) As Boolean
            Dim bResult As New Boolean()
            bResult = False
            Dim hEMF, hEMF2 As IntPtr
            hEMF = mf.GetHenhmetafile() ' invalidates mf
            If Not hEMF.Equals(New IntPtr(0)) Then
                hEMF2 = CopyEnhMetaFile(hEMF, New IntPtr(0))
                If Not hEMF2.Equals(New IntPtr(0)) Then
                    If OpenClipboard(hWnd) Then
                        If EmptyClipboard() Then
                            Dim hRes As IntPtr
                            hRes = SetClipboardData(14, hEMF2)    ' 14 == CF_ENHMETAFILE
                            bResult = hRes.Equals(hEMF2)
                            CloseClipboard()
                        End If
                    End If
                End If
                DeleteEnhMetaFile(hEMF)
            End If
            Return bResult
        End Function
    
        Private Sub AddImageToRtb(ByVal imgPathName As String)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
    
            'Create a graphics object of the Form and get its hdc handle
            Dim me_grx As Graphics = Me.CreateGraphics()
            Dim me_hdc As IntPtr = me_grx.GetHdc()
    
            'Create a new metafile the same size as the image and create a graphics object for it
            Dim emf As New Metafile("Tmp.emf", me_hdc, New Rectangle(0, 0, bm.Width, bm.Height), MetafileFrameUnit.Pixel)
            Dim emf_gr As Graphics = Graphics.FromImage(emf)
    
            'Draw the bitmap image onto the new metafile
            emf_gr.DrawImage(bm, 0, 0)
    
            'Dispose the bitmap and the metafile graphics object
            emf_gr.Dispose()
            bm.Dispose()
    
            'Copy the new metafile to the clipboard
            PutEnhMetafileOnClipboard(Me.Handle, emf)
    
            'Paste the new metafile in the RichTextBox
            RichTextBox1.Paste()
    
            'Dispose the rest of the objects we created
            me_grx.ReleaseHdc(me_hdc)
            me_grx.Dispose()
            emf.Dispose()
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim ofd As New OpenFileDialog
            ofd.Title = "Add Image..."
            ofd.Filter = "Images|*.jpg;*.bmp;*.png"
            ofd.Multiselect = False
            If ofd.ShowDialog = DialogResult.OK Then
                AddImageToRtb(ofd.FileName)
            End If
            ofd.Dispose()
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim sfd As New SaveFileDialog
            sfd.Title = "Save File..."
            sfd.FileName = "Untitled"
            sfd.DefaultExt = "rtf"
            sfd.AddExtension = True
            If sfd.ShowDialog = DialogResult.OK Then
                RichTextBox1.SaveFile(sfd.FileName, RichTextBoxStreamType.RichText)
            End If
            sfd.Dispose()
        End Sub
    End Class
    


    EDIT : Updated code so that no temporary images are saved on the hard drive. Again thanks to JohnWein`s help with this.

    • Edited by IronRazerz Wednesday, January 15, 2014 2:17 AM
    • Marked as answer by Carl Andersson Wednesday, January 15, 2014 4:10 PM
    Tuesday, January 14, 2014 11:02 PM

All replies

  • The links was interesting but some of them that really could help me in my problem was in vb 6 and im using Visual Basic 2012. The code is not the same so it dont work. Is there some updated methods that can be used in the newer versions of vb? 
    Tuesday, January 7, 2014 5:56 PM
  • The following appears to work fine when the image is resized in the document; obviously the image gets pixelated if you increase the size, but that is to be expected - the colors stay as they should.

    Clipboard.SetData(DataFormats.Bitmap, Image.FromFile("C:\folder\imagename.png")) 'change this to a real image on your pc
    
    RichTextBox1.AppendText("this is the first line of text.")
    RichTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap))
    RichTextBox1.AppendText("this is the next line of text.")
    

    If this isn't working for you, can you tell us the image format of your bitmaps?


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Tuesday, January 7, 2014 6:11 PM
  • Hi there!

    After i ever used the method to use the clipboard to insert images in to richtextbox. I see that when resizing the image, it get a very messed up color and quality. I was reseaching this and there is two ways as i saw. Using the Clipboard or using OLE objects. But these makes the color messed up, because its not real rtf code. The image has just been pasted right in, its not real rtf image code. There was a guy that found annother way to insert images that i think was called stdpicast. I got an pdf where he demonstrate how this is working and an zip file with the source project. The problem is that the project is in VB 6 format. Anyway, someone know how to insert images in this way or can convert the code in the zip of some kind?

    Thank you!

    PDF: Direct Download

    ZIP: Direct Download

    Since reading your post I've been researching this. And I also find when reducing the size of an image in a RichTextBox the quality becomes really poor.

    So what I've found so far is code for copying an image into a RTB from the clipboard. Clearing the clipboard and copying an image from an RTB to the clipboard. As well as code that detects in an RTB mouse down event if the selection type is an object. Although there is also code available to detect if the selection is an image which I may end up using as I don't know if an RTB object is always an image.

    Anyhow I figure the RTB mouse down, mouse move and mouse up events will be required. For mouse down if the selection is an image clear the clipboard and copy the image to the clipboard. Then copy that to a new bitmap.

    For mouse move clear the clipboard, copy the image to the clipboard, check the clipboard images width and height. Although mouse move may not be required.

    For mouse up clear the clipboard. Copy the image to the clipboard. Check the clipboard images width and height. Use graphics to resize the bitmap image to whatever size the clipboard image is with System.Drawing.Drawing2D graphics.InterpolationMode which should provide a high quality reduced or enlarged image and then delete the image at the selection in the RTB replacing it with the new bitmap image. Clear the clipboard.

    It may be a couple of hours till I get it done and see if it actually works as I need to eat and take care of some things for now.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.


    Tuesday, January 7, 2014 6:38 PM
  • Make a Metafile from your image and Use RichTextBox.Paste.
    Tuesday, January 7, 2014 7:33 PM
  • I have heard about metafile. But how do i make one from an image?
    Tuesday, January 7, 2014 7:51 PM
  • You don't.  You construct a Metafile from the choice of constructors listed in Help and draw your image to it.
    Tuesday, January 7, 2014 8:49 PM
  • I have heard about metafile. But how do i make one from an image?

    Well there's a few issues with the possible solution I wanted to propose.

    First when an image is pasted into a RichTextBox from the clip board and is then resized its actual image size apparently does not change. Because after the clip board is cleared and the image in the RichTextBox is sized much smaller it can be copied back to the clip board and its size in the clip board is the same as it was when the image was first pasted into the RichTextBox from the clip board.

    The only changes I saw were changes to the images metadata, I guess it is called, which I suppose pertains to how the RichTextBox displays the image.

    In the image below the top picture is an image pasted into a RichTextBox before resizing. The same image is in the PictureBox to the right of the RichTextBox which was resized smaller using "graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic". The bottom picture in the image below is the image in the RichTextBox resized to approximately the same size as the image in the PictureBox. You can see the loss of quality in the RichTextBox image.

    Below is the "metadata" of the top pictures RichTextBox image followed by the "metadata" of the bottom pictures RichTextBox image. You can see how the picw, pich, picwgoal and pichgoal values changed. It may not be too difficult to figure how to use those values (I haven't really looked at them yet) with an actual bitmap to adjust the bitmaps size and replace the image in the RichTextBox with a high quality interpolated bitmap.

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
    \uc1\pard\f0\fs29{\pict\wmetafile8\picw8148\pich6931\picwgoal4619\pichgoal3929
    
    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
    \uc1\pard\f0\fs29{\pict\wmetafile8\picw2514\pich2275\picwgoal1425\pichgoal1290 

    The issue I see is that if you downsize the image in the RTB and replace it with a high quality image then the new high quality image will be whatever size it is instead of the original size of the original image pasted into the RTB. So if you attempt to resize the small image larger there will be loss at some point. If the original image pasted into the RTB were still available though then it could always be used when resizing occurs to enlarge or reduce a copy of it. Then replace the image in the RTB after it is resized.

    So basically when an image is pasted into an RTB save a copy of it to a list(of Image) or something. Then read its metadata and store it. If it is resized wait until the resizing is done, read its new metadata, figure out what size the original image was, enlarge or decrease its size according to the metadata before and after values and replace it with a new bitmap image copied to the clipboard for pasting into the RTB.

    And be able to do this for multiple images in an RTB. I would guess something in an RTB images metadata can denote it from another RTB image.

    So maybe sometime tomorrow I may end up being able to do it or maybe not.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Wednesday, January 8, 2014 3:51 AM
  • I dont know but i searched the web and i found this:

    http://www.codeproject.com/Questions/540673/answer.aspx

    It seems that may solutions is in C# and that irritates me.

    Wednesday, January 8, 2014 8:31 PM
  • What problems are you having with pasting a metafile?
    Wednesday, January 8, 2014 8:34 PM
  • Ok now, i use this code for addin my images right now:

            OpenImage.ShowDialog()
            If OpenImage.FileName = "" Then
    
            Else
                Dim img As Image = Image.FromFile(OpenImage.FileName)
                Dim orgData = Clipboard.GetDataObject
                Clipboard.SetImage(img)
                Me.RichTextBox1.Paste()
    
                Clipboard.SetDataObject(orgData)
            End If

    And when i resize the image it gets like this:

    Programs such as WordPad using something like(if i understood it right):

    1. Create a EMF file from the image
    2. Convert it to WMF.
    3. Convert the bytes to hexademicals.

    Programs like WordPad is using an convertion to make the image correct in resize.

    Wednesday, January 8, 2014 8:49 PM
  • Ok now, i use this code for addin my images right now:

            OpenImage.ShowDialog()
            If OpenImage.FileName = "" Then
    
            Else
                Dim img As Image = Image.FromFile(OpenImage.FileName)
                Dim orgData = Clipboard.GetDataObject
                Clipboard.SetImage(img)
                Me.RichTextBox1.Paste()
    
                Clipboard.SetDataObject(orgData)
            End If

    And when i resize the image it gets like this:

    Programs such as WordPad using something like(if i understood it right):

    1. Create a EMF file from the image
    2. Convert it to WMF.
    3. Convert the bytes to hexademicals.

    Programs like WordPad is using an convertion to make the image correct in resize.


    Just construct a metafile and draw your image to it.  Copy the metafile to the Clipboard and paste to your rich text box.  I don't know how to make it any simpler.
    Wednesday, January 8, 2014 10:04 PM
  • I dont know but i searched the web and i found this:

    http://www.codeproject.com/Questions/540673/answer.aspx

    It seems that may solutions is in C# and that irritates me.

     Try using one of the free online C# to VB.Net converters to convert some of the C# examples. You may need to do small parts of the code at a time because, some of them only allow you to convert a limited length of code.

    http://converter.telerik.com/

    http://www.developerfusion.com/tools/convert/csharp-to-vb/

    Wednesday, January 8, 2014 10:55 PM
  • Please give me the code that can make the metafile then. I dont know how to do one.
    Thursday, January 9, 2014 12:43 PM
  • Please give me the code that can make the metafile then. I dont know how to do one.
    If your coding capabilities are limited to transcribing code, you should contract with a coder.
    Thursday, January 9, 2014 1:37 PM
  • Ok, i end this post now. This not seems to work. There is no way to get good quality and color in RichTextBox while resizing an image.

    End

    Thursday, January 9, 2014 6:56 PM
  • Ok, i end this post now. This not seems to work. There is no way to get good quality and color in RichTextBox while resizing an image.

    End

    I'm still working on it but it's taking some time to develop how to do it. As it will require a capability not designed in the RichTextBox.

    So after resizing an image an update button or something will be required to be pressed in order to replace the image in the RTB with a high quality conversion of it. As well as saving the original image from the RTB in case it needs to be resized again.

    I doubt I will be done before the weekend though. But I'll post the code when I'm done whether you want it or not.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.




    Thursday, January 9, 2014 7:24 PM
  • Ok, i end this post now. This not seems to work. There is no way to get good quality and color in RichTextBox while resizing an image.

    This rich text format file contains an image that can be resized by right-clicking on the image and dragging the sizing handles.


    • Edited by JohnWein Tuesday, January 14, 2014 6:05 AM
    Thursday, January 9, 2014 8:00 PM
  • Ok, if you still working on a solution, thanks!
    I think we still keep this thread up for a bit. Because i think there is many more than me that want to know how to do this.


    Friday, January 10, 2014 4:20 PM
  • I'm still working on this but I've other things to do and it's a real difficult implementation for me to develop so it may be a few more days before I have a possible solution that is accepatable for me to post. If I don't have it done by 17 Jan then I will post that I can not implement it and the reasons why I can not do it. But I will post the code I have too in case you or somebody else can figure it out.

    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Tuesday, January 14, 2014 1:13 AM
  • "But I will post the code I have too in case you or somebody else can figure it out."

    What's to figure out? 

    The procedure hasn't changed since the early 90's:  Construct a metafile and draw your image to it.  Copy the metafile to the Clipboard and paste to your rich text box.  The only tricky part is knowing to use the ClipboardMetafileHelper.


    • Edited by JohnWein Tuesday, January 14, 2014 1:36 AM
    Tuesday, January 14, 2014 1:35 AM
  • "But I will post the code I have too in case you or somebody else can figure it out."

    What's to figure out? 

    The procedure hasn't changed since the early 90's:  Construct a metafile and draw your image to it.  Copy the metafile to the Clipboard and paste to your rich text box.  The only tricky part is knowing to use the ClipboardMetafileHelper.


    And after the image is resized and loses its quality when resized what then? Resize your image using a third party application then create a new metafile for the resized image and copy and paste that into the RichTextBox?

    I'm not attempting that. I'm attempting to resize the image with quality reisizing seperately after it is resized in the RichTextBox to the RichTextBoxs new size of the original image. Then replace the image in the RichTextBox which lost its quality when resized with the resized image that didn't lose its quality when resized to the same size as the RichTextBoxs image. As well as saving the original image pasted into the RichTextBox in case any further resizing of it needs to be performed.

    If you look at the 8th reply post to the original question you will see in the second picture of the image the loss of quality that occured in the RichTextBox resize compared to the same image resized in a PictureBox using the appropriate method to resize the image.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Tuesday, January 14, 2014 3:08 AM
  • "And after the image is resized and loses its quality when resized what then?"

    If you pasted a metafile and it loses quality excessively when it's resized, you're doing something incorrectly.  You can't resize an image with better fidelity than you can using a metafile.  It always resizes the original image.

    Tuesday, January 14, 2014 3:49 AM
  • "And after the image is resized and loses its quality when resized what then?"

    If you pasted a metafile and it loses quality excessively when it's resized, you're doing something incorrectly.  You can't resize an image with better fidelity than you can using a metafile.  It always resizes the original image.

    Then why did the image resized in the RichTextBox in the post I previously referenced lose its quality while the same image resized using appropriate code to resize it in the PictureBox did not lose its quality?

    Have you bothered to resize an image in a RichTextBox in order to see what occurs? I figure the post referenced shows exactly what occurs. So it's obviously apparent to me that a RichTextBox does not peform image resizing accurately according to the metadata it is supposedly using when resizing occurs. Therefore I'm not sure why you keep insisting on the metadata aspect.

    When I was in the military there was a term used called "GIGO" (pronounced Ghee-Go). It's meaning is Garbage In Garbage Out. The RichTextBox metadata for performing resizing provides Garbage Out.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.






    Tuesday, January 14, 2014 4:20 AM
  • JohnWein, I have just tested your theory extensively. If you draw a standard image onto a metafile and paste it into the RichTextBox, it will resize just as any other standard image with excessive quality loss. I think one way to overcome this would be to try and inherit a new control from the RichTextBox and try to handle this event in a different manner, Either way, good luck with your endeavor, Mr. Monkeyboy. Hope you get it figured out for HV-Developing Team.

    Thanks, Jayson Furr Jayson.Furr@FuJeSolutions.com

    Tuesday, January 14, 2014 4:23 AM
  • JohnWein, I have just tested your theory extensively. If you draw a standard image onto a metafile and paste it into the RichTextBox, it will resize just as any other standard image with excessive quality loss.

    You're doing something wrong.  Post your code. 

    As I replied to Mr. Monkeybox, if you used exactly the same code in the Metafile as you used to resize the image anywhere else, the results should be identical.  A metafile only draws what you have programmed it to draw.  If you don't get results comparable to what you can achieve in another manner, you haven't programmed the metafile correctly.

    • Edited by JohnWein Tuesday, January 14, 2014 6:10 AM
    Tuesday, January 14, 2014 5:27 AM
  • "Then why did the image resized in the RichTextBox in the post I previously referenced lose its quality while the same image resized using appropriate code to resize it in the PictureBox did not lose its quality?"

    Because you have not pasted a metafile in the RichTextBox.  Metadata and metafiles are completely different objects. 

    If you used exactly the same code in the Metafile as you used in the PictureBox, the results should be identical. 

    Tuesday, January 14, 2014 5:34 AM
  • You're doing something wrong.  Post your code.

     Hi John,

     I checked out your RichText Format File that you posted the other day and that seemed to resize and keep its quality really nice. The link seems to be broken now but, i wanted to ask if that was an rtf document you made using a metafile ? I have been banging my head off the wall and pulling my hair out just trying to figure out how to even copy a dang jpg, png, or bmp into a metafile. I get nothing but GDI errors with everything i try. Are you using API`s to do that or just .net methods ?


    • Edited by IronRazerz Tuesday, January 14, 2014 5:45 AM
    Tuesday, January 14, 2014 5:45 AM
  • You're doing something wrong.  Post your code.

     Hi John,

     I checked out your RichText Format File that you posted the other day and that seemed to resize and keep its quality really nice. The link seems to be broken now but, i wanted to ask if that was an rtf document you made using a metafile ? I have been banging my head off the wall and pulling my hair out just trying to figure out how to even copy a dang jpg, png, or bmp into a metafile. I get nothing but GDI errors with everything i try. Are you using API`s to do that or just .net methods ?


    Just .NET methods.  I'm willing to help, but I'm not an on-demand coder.  I find the simplest metafile is a file based metafile.  Construct the metafile using a Form's device context.  That is, use CreateGraphics and then GetHdc.  Draw the image to it and then dispose the metafile.  Use the ClipboardMetafileHelper to paste the metafile in the RichTextBox.

    Post the code you're having problems with.

    I restored the link to the .rtf file on my Skydrive.

    • Edited by JohnWein Tuesday, January 14, 2014 6:14 AM
    Tuesday, January 14, 2014 5:57 AM
  • @ JohnWein,

     Ahhh, i see. I was trying to use the hdc handle from a new bitmaps graphics. I will have to play with this some more tomorrow. It`s getting late here. I never used a metafile for anything so this has all been a new learning experience for me following this thread for the last few days. I already checked out the link you gave for the ClipboardMetafileHelper. If i can`t get it going i will post a new question in the next few days so i am not filling this one with my questions. Thanks for the tips.   :)

    Tuesday, January 14, 2014 6:16 AM
  • You're doing something wrong.  Post your code.

     Hi John,

     I checked out your RichText Format File that you posted the other day and that seemed to resize and keep its quality really nice. The link seems to be broken now but, i wanted to ask if that was an rtf document you made using a metafile ? I have been banging my head off the wall and pulling my hair out just trying to figure out how to even copy a dang jpg, png, or bmp into a metafile. I get nothing but GDI errors with everything i try. Are you using API`s to do that or just .net methods ?


    Just .NET methods.  I'm willing to help, but I'm not an on-demand coder.  I find the simplest metafile is a file based metafile.  Construct the metafile using a Form's device context.  That is, use CreateGraphics and then GetHdc.  Draw the image to it and then dispose the metafile.  Use the ClipboardMetafileHelper to paste the metafile in the RichTextBox.

    Post the code you're having problems with.

    I restored the link to the .rtf file on my Skydrive.

    So I suppose the RTB image resize doesn't work very well. And therefore a metafile of somesort has to be created after the image is drawn to something which I would suppose the user would be required to know ahead of time what size they want the image to become in the RTB before pasting the metafile in the RTB. Does this also require deleting the original image that was pasted into the RTB?

    I would guess that using the RTBs resize capability would be necessary in the first place as the user is attempting to adjust the size of the image to fit in the RTB at a specific location surrounded by text and stuff before they know what the actual size necessary for the metafile would be. So I don't really see a relevant solution with this.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Tuesday, January 14, 2014 7:39 PM
  • So I suppose the RTB image resize doesn't work very well. And therefore a metafile of somesort has to be created after the image is drawn to something which I would suppose the user would be required to know ahead of time what size they want the image to become in the RTB before pasting the metafile in the RTB. Does this also require deleting the original image that was pasted into the RTB?

    I would guess that using the RTBs resize capability would be necessary in the first place as the user is attempting to adjust the size of the image to fit in the RTB at a specific location surrounded by text and stuff before they know what the actual size necessary for the metafile would be. So I don't really see a relevant solution with this.

     Hi Mr. Monkeyboy,

      Maybe i am not following your question correctly but, if the user has selected an image then you can use that image`s size to set the size of the metafile when your creating it and pasting it in the RichTextBox.

     I just got 1 version finished about an hour ago and have been cleaning it up and commenting some of it. It seems to work pretty good. The only part i don`t care for is i am saving the metafile to the hard drive and then re-opening it again to use the ClipboardMetafileHelper to copy it to the clipboard and then pasting it in the RichTextBox. I am going to start on another version to see if i can copy it to a MemoryStream and then to the clipboard so i can eliminate saving it to the hard drive first. I have to go eat so i will send an email or maybe post it here for others to check out.  :)


    • Edited by IronRazerz Wednesday, January 15, 2014 4:25 PM
    Tuesday, January 14, 2014 8:50 PM
  • Hello Everyone,

     This is an example i made of creating a Metafile from an image on your hard drive and pasting it into a RichTextBox. This method will produce a much better quality image than just pasting a standard bitmap image into your RichTextBox. You can re-size the image to the size of a postal stamp or to the size of the whole RichTextBox without  making your image look blurry and discolored. I commented the AddImageToRtb sub that i wrote so it should be fairly easy for anyone to understand the steps i took to do this. I don`t claim this to be a prize winning masterpiece but, it works pretty good.

     I also want to say Thanks Again to JohnWein for helping point me in the rite direction for doing this and for the helpful link he provided to the ClipboardMetafileHelper code which contains the PutEnhMetafileOnClipboard function i used in this example.

     You can test this example by creating a new Windows Form Application project and placing 2 Buttons and 1 RichTextBox onto the Form. Button1 will allow you to select an image from your hard drive to add to the RichTextBox. Button2 will allow you to save your Rich Text File to your hard drive. Have Fun!!!

    Imports System.Drawing.Imaging
    Imports System.Runtime.InteropServices
    
    Public Class Form1
        <DllImport("user32.dll", EntryPoint:="OpenClipboard")> Private Shared Function OpenClipboard(ByVal hWnd As IntPtr) As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="EmptyClipboard")> Private Shared Function EmptyClipboard() As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="SetClipboardData")> Private Shared Function SetClipboardData(ByVal uFormat As Integer, ByVal hWnd As IntPtr) As IntPtr
        End Function
        <DllImport("user32.dll", EntryPoint:="CloseClipboard")> Private Shared Function CloseClipboard() As Boolean
        End Function
        <DllImport("gdi32.dll", EntryPoint:="CopyEnhMetaFileA")> Private Shared Function CopyEnhMetaFile(ByVal hemfSrc As IntPtr, ByVal hNULL As IntPtr) As IntPtr
        End Function
        <DllImport("gdi32.dll", EntryPoint:="DeleteEnhMetaFile")> Private Shared Function DeleteEnhMetaFile(ByVal hemfSrc As IntPtr) As Boolean
        End Function
    
        'I do not claim to have written the PutEnhMetafileOnClipboard function.
        'For more information on this function and why it is needed refer to http://support.microsoft.com/kb/323530/en-us
        Private Shared Function PutEnhMetafileOnClipboard(ByVal hWnd As IntPtr, ByVal mf As Metafile) As Boolean
            Dim bResult As New Boolean()
            bResult = False
            Dim hEMF, hEMF2 As IntPtr
            hEMF = mf.GetHenhmetafile() ' invalidates mf
            If Not hEMF.Equals(New IntPtr(0)) Then
                hEMF2 = CopyEnhMetaFile(hEMF, New IntPtr(0))
                If Not hEMF2.Equals(New IntPtr(0)) Then
                    If OpenClipboard(hWnd) Then
                        If EmptyClipboard() Then
                            Dim hRes As IntPtr
                            hRes = SetClipboardData(14, hEMF2)    ' 14 == CF_ENHMETAFILE
                            bResult = hRes.Equals(hEMF2)
                            CloseClipboard()
                        End If
                    End If
                End If
                DeleteEnhMetaFile(hEMF)
            End If
            Return bResult
        End Function
    
        Private Sub AddImageToRtb(ByVal imgPathName As String)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
    
            'Create a graphics object of the Form and get its hdc handle
            Dim me_grx As Graphics = Me.CreateGraphics()
            Dim me_hdc As IntPtr = me_grx.GetHdc()
    
            'Create a new metafile the same size as the image and create a graphics object for it
            Dim emf As New Metafile("Tmp.emf", me_hdc, New Rectangle(0, 0, bm.Width, bm.Height), MetafileFrameUnit.Pixel)
            Dim emf_gr As Graphics = Graphics.FromImage(emf)
    
            'Draw the bitmap image onto the new metafile
            emf_gr.DrawImage(bm, 0, 0)
    
            'Dispose the bitmap and the metafile graphics object
            emf_gr.Dispose()
            bm.Dispose()
    
            'Copy the new metafile to the clipboard
            PutEnhMetafileOnClipboard(Me.Handle, emf)
    
            'Paste the new metafile in the RichTextBox
            RichTextBox1.Paste()
    
            'Dispose the rest of the objects we created
            me_grx.ReleaseHdc(me_hdc)
            me_grx.Dispose()
            emf.Dispose()
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim ofd As New OpenFileDialog
            ofd.Title = "Add Image..."
            ofd.Filter = "Images|*.jpg;*.bmp;*.png"
            ofd.Multiselect = False
            If ofd.ShowDialog = DialogResult.OK Then
                AddImageToRtb(ofd.FileName)
            End If
            ofd.Dispose()
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim sfd As New SaveFileDialog
            sfd.Title = "Save File..."
            sfd.FileName = "Untitled"
            sfd.DefaultExt = "rtf"
            sfd.AddExtension = True
            If sfd.ShowDialog = DialogResult.OK Then
                RichTextBox1.SaveFile(sfd.FileName, RichTextBoxStreamType.RichText)
            End If
            sfd.Dispose()
        End Sub
    End Class
    


    EDIT : Updated code so that no temporary images are saved on the hard drive. Again thanks to JohnWein`s help with this.

    • Edited by IronRazerz Wednesday, January 15, 2014 2:17 AM
    • Marked as answer by Carl Andersson Wednesday, January 15, 2014 4:10 PM
    Tuesday, January 14, 2014 11:02 PM
  • "This is an example i made of creating a Metafile from an image on your hard drive and pasting it into a RichTextBox."  Every thing looks good.  The key points are that you have to understand metafiles and p/invoking the native API to use the native clipboard. 

    Here is the code I used.  I suggested using a file for the metafile first as it saves code.

    Imports System.Drawing.Imaging
    Imports System.IO
    Public Class Form1
      
    Dim WithEvents MS As New MenuStrip
      
    Dim WithEvents RTB As New RichTextBox
      
    Protected Overrides Sub OnLoad(e As EventArgs)
        
    MyBase.OnLoad(e)
        MS.Items.Add(
    New ToolStripButton("Open"))
        MS.Items.Add(
    New ToolStripButton("Save"))
        MS.Parent = 
    Me
        RTB.Parent = 
    Me
        RTB.BringToFront()
        RTB.Dock = 
    DockStyle.Fill
      
    End Sub
      
    Private Sub MS_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgsHandles MS.ItemClicked
        
    Select Case e.ClickedItem.Text
          
    Case "Open"
            OpenImage()
          
    Case "Save"
            SaveRTF()
        
    End Select
      
    End Sub
      
    Sub OpenImage()
        
    Dim OFD As New OpenFileDialog
        
    If Not OFD.ShowDialog = DialogResult.OK Then Return
        
    Using G As Graphics = Me.CreateGraphics
          
    Dim hDC As IntPtr = G.GetHdc
          
    Using MF As New Metafile("Metafile.wmf", hDC)
            
    Using Bmp As New Bitmap(OFD.FileName)
              
    Using GMF As Graphics = Graphics.FromImage(MF)
                GMF.DrawImage(Bmp, 0, 0)
              
    End Using
            
    End Using
            
    ClipboardMetafileHelper.PutEnhMetafileOnClipboard(Me.Handle, MF)
          
    End Using
          G.ReleaseHdc(hDC)
        
    End Using
        RTB.Paste()
      
    End Sub
      
    Sub SaveRTF()
        
    Dim SFD As New SaveFileDialog
        SFD.FileName = 
    "Metafile.rtf"
        
    If Not SFD.ShowDialog = DialogResult.OK Then Return
        RTB.SaveFile(SFD.FileName, 
    RichTextBoxStreamType.RichText)
      
    End Sub
    End Class
    Public Class ClipboardMetafileHelper 'Condensed from http://support.microsoft.com/kb/323530/en-us

      
    Declare Function OpenClipboard Lib "user32" (hWnd As IntPtrAs Boolean
      
    Declare Function EmptyClipboard Lib "user32" () As Boolean
      
    Declare Function SetClipboardData Lib "user32" (uFormat As Integer, hWnd As IntPtrAs IntPtr
      
    Declare Function CloseClipboard Lib "user32" () As Boolean
      
    Declare Auto Function CopyEnhMetaFile Lib "gdi32.dll" (hemfSrc As IntPtr, hNULL As IntPtrAs IntPtr
      
    Declare Function DeleteEnhMetaFile Lib "gdi32.dll" (hemfSrc As IntPtrAs Boolean

      
    Friend Shared Function PutEnhMetafileOnClipboard(hWnd As IntPtr, mf As MetafileAs Boolean
        
    Dim bResult As Boolean
        
    Dim hEMF As IntPtr = mf.GetHenhmetafile() ' invalidates mf
        
    If hEMF.Equals(IntPtr.Zero) Then Return bResult
        
    Dim hEMF2 As IntPtr = CopyEnhMetaFile(hEMF, New IntPtr(0))
        
    If hEMF2.Equals(IntPtr.Zero) Then Return bResult
        
    If OpenClipboard(hWnd) Then
          
    If EmptyClipboard() Then
            
    Dim hRes As IntPtr = SetClipboardData(14, hEMF2)    ' 14 == CF_ENHMETAFILE
            bResult = hRes.Equals(hEMF2)
            CloseClipboard()
          
    End If
        
    End If
        DeleteEnhMetaFile(hEMF)
        
    Return bResult
      
    End Function

    End Class



    • Edited by JohnWein Tuesday, January 14, 2014 11:43 PM
    • Proposed as answer by Jayson Furr Wednesday, January 15, 2014 12:09 AM
    Tuesday, January 14, 2014 11:28 PM
  • "This is an example i made of creating a Metafile from an image on your hard drive and pasting it into a RichTextBox."  Every thing looks good.  The key points are that you have to understand metafiles and p/invoking the native API to use the native clipboard. 

    Here is the code I used.  I suggested using a file for the metafile first as it saves code.

     Thanks John. I think yours is coded quite a bit better though. I should have used "Using" blocks which is better that worrying about disposing everything. I also see you are only creating 1 metafile and drawing the image on it. Then after the End Using statement your copying it rite to the clipboard. I kept getting an error in the PutEnhMetafileOnClipboard sub if i tried disposing the metafile and then tried to copy it to the clipboard. I will have to re-investigate that in my code to see if it is something to do with the the Using/End Using blocks or perhaps something else.

     As i say, the metafile is a whole new beast to me. I am trying to figure it out as i go by reading the msdn documents and whatever i can find on the net. You have definitely helped me to get things going by tipping me off on creating the graphics from the form and using the hdc handle from that. Also the link for the PutEnhMetafileOnClipboard code. Using native API functions is something i am very familiar with but, i didn`t ever use any of the clipboard functions. It is always nice to pick something new up though.

     Anyways, i am going to check your code out in a project and see what else i can learn from it.   :)

    EDIT : I was mistaken. You are only disposing the metafile graphics object before copying it to the clipboard and not the metafile. I have updated my code to fix that. I thought you where saying to dispose the metafile before copying it to the clipboard which was why i was creating the 2nd medafile.

    • Edited by IronRazerz Wednesday, January 15, 2014 2:23 AM
    Wednesday, January 15, 2014 12:36 AM
  • There we got it! Thank you so much IronRazerz!!

    The code worked like a charm. Thank you!

    Thanks to all of you that have spend your time on this thread! Im so happy it works! Good job everybody!




    Wednesday, January 15, 2014 4:11 PM
  • There we got it! Thank you so much IronRazerz!!

    The code worked like a charm. Thank you!

    Thanks to all of you that have spend your time on this thread! Im so happy it works! Good job everybody!


     Your Welcome.    :)
    Wednesday, January 15, 2014 4:23 PM
  • And one last thing if you dont mind.

    If i paste the image using your code, can i change the images size in the code? The size of the image when it is pasted so it cant be super huge. I mean that its resized to a small image directly when pasted.

    Wednesday, January 15, 2014 4:41 PM
  • Hi,

     Yes, you could try adding another parameter to the AddImgToRtb sub and re-size the bitmap that you are opening. However, that may distort the image before it even gets copied to the metafile depending on the image and the amount you are shrinking it. You could try using some Graphics methods to redraw the bitmap onto another bitmap to try keeping as much quality as possible before copying it to the metafile. I will have to look into that and do some experimenting.

        Private Sub AddImageToRtb(ByVal imgPathName As String, ByVal startsize As Size)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
            bm = New Bitmap(bm, startsize.Width, startsize.Height)
    
    

    Then call the sub with the image pathname and the size you want it to be.

                AddImageToRtb(ofd.FileName, New Size(200, 150))
    

    Wednesday, January 15, 2014 5:07 PM
  • Hi,

     Yes, you could try adding another parameter to the AddImgToRtb sub and re-size the bitmap that you are opening. However, that may distort the image before it even gets copied to the metafile depending on the image and the amount you are shrinking it. You could try using some Graphics methods to redraw the bitmap onto another bitmap to try keeping as much quality as possible before copying it to the metafile. I will have to look into that and do some experimenting.

        Private Sub AddImageToRtb(ByVal imgPathName As String, ByVal startsize As Size)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
            bm = New Bitmap(bm, startsize.Width, startsize.Height)
    

    Then call the sub with the image pathname and the size you want it to be.

                AddImageToRtb(ofd.FileName, New Size(200, 150))


    You don't want to do it that way.  You want to do it as word does:  resize the metafilepict after it's pasted.  The OP should ask a new question for this.
    Wednesday, January 15, 2014 5:15 PM
  • You don't want to do it that way.  You want to do it as word does:  resize the metafilepict after it's pasted.  The OP should ask a new question for this.
     That is why i wanted to do some more reading and experimenting with it. I was not sure if there was a way to re-size the metafile prior to copying it to the clipboard or after pasting it in the RichTextBox as you mentioned. Like i said, this would probably distort the image and that is the whole purpose of using the metafile in the first place. That is kind of like giving your car a new paint job before taking it to the demolition derby. haha.   :)
    Wednesday, January 15, 2014 5:29 PM
  • That is kind of like giving your car a new paint job before taking it to the demolition derby. haha.   :)


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Wednesday, January 15, 2014 5:34 PM
  • This method:

        Private Sub AddImageToRtb(ByVal imgPathName As String, ByVal startsize As Size)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
            bm = New Bitmap(bm, startsize.Width, startsize.Height)
    Worked! I think. Anyway, i think we are compelete here now! Thanks again to all advice that has been posted! Thanks!

    Wednesday, January 15, 2014 6:39 PM
  • This method:

        Private Sub AddImageToRtb(ByVal imgPathName As String, ByVal startsize As Size)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
            bm = New Bitmap(bm, startsize.Width, startsize.Height)
    Worked! I think. Anyway, i think we are compelete here now! Thanks again to all advice that has been posted! Thanks!


     If it works for what your doing then that is great. However, i will still see what i can come up with from JohnWein`s suggestion. I will post it here if i come up with a something good.   :)
    Wednesday, January 15, 2014 6:47 PM
  • This method:

        Private Sub AddImageToRtb(ByVal imgPathName As String, ByVal startsize As Size)
            'Create a bitmap of the image you want to draw to the metafile
            Dim bm As New Bitmap(imgPathName)
            bm = New Bitmap(bm, startsize.Width, startsize.Height)
    Worked! I think. Anyway, i think we are compelete here now! Thanks again to all advice that has been posted! Thanks!

    Off to the races. 

    To retain quality, the metafilepict has to be resized.  Select the image.  Cast the Object to a metafilepict and change its size using the API structure.

    Wednesday, January 15, 2014 6:52 PM
  • Off to the races. 

    To retain quality, the metafilepict has to be resized.  Select the image.  Cast the Object to a metafilepict and change its size using the API structure.

     Yep. It has my mind going 100 mph again. I am working on it but, i am having trouble figuring out how to get the selected object from the richtextbox so i can cast it to a metafile. I will have to take a long look at the msdn docs on the richtextbox methods and see if i can dig anything up from there. It probably does not help that medafiles are all new to me also. If i don`t figure it out by tomorrow i will probably post a new question because this thread is getting to be a mile long and this does not really have to do with the original question. Besides that it will drive me crazy if i don`t figure it out now that i started.   :)
    Wednesday, January 15, 2014 8:13 PM
  • I know you ended this thread but I said I would post the code for my solution even if you found another solution.

    How this works.

    When an image is to be resized then left click in the middle of the image. This will add its RTF metadata to a list(Of string) for its current size according to the metadata as the list(Of Strings) first entry. It also brings up the images resizing things (the little squares for resizing the image).

    When the image is finished being resized then left click in the middle of the image. This will add its new RTF metadata to the list(Of String) as the last entry.

    If you want to replace the RTB's resized image with a good quality image then after the left click, with the cursor still on the image then right click. A MessageBox will ask if you want to replace the RTB image with a high quality resize of it.

    Anyhow if you continually reduce the size of the image it works fine. However if you want to enlarge a reduced sized image the quality gets poorer and poorer the larger it gets. Therefore the image in the RTB should be deleted and reloaded which may not be possible depending on how the image was placed in the clipboard (like from some website where you forgot the location of the image or something).

    If you want to increase the original images size it seems to work fine up to some point I would guess when the quality starts becoming poorer. Although you can continually reduce the size of an enlarged image with no apparent loss of quality if the enlarged image looked good after the last enlargement.

    I also tested it by placing an image at the top of the RTB and below that adding some words then adding the image again and adding some more words. Then reducing the size of the image between the words to make sure this would not affect the image in the top of the RTB and it appeared to work fine.

    And you don't need the PictureBox. It's just there for testing purposes. You could use a Bitmap to hold the image instead I believe.

    Option Strict On
    
    Imports System.Runtime.InteropServices
    Imports System.Drawing.Drawing2D
    
    Public Class Form1
    
        ' For question in thread http://social.msdn.microsoft.com/Forums/en-US/355bfc59-cd0a-4e81-984e-9f066fd3a897/richtextbox-images-quality-loss?forum=vbgeneral
    
        ' NOTE: Using Clipboard.Clear causes the app to malfunction at some point or Visual Studio to quit working if app is running
        ' in debugger. And Visual Studio will not work again until the PC is rebooted.
    
        <DllImport("user32.dll")> _
        Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
        End Function
    
        Private Const WM_COPY = &H301
    
        Dim RTBMetaInfo As New List(Of String)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.CenterToScreen()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Clipboard.SetImage(Image.FromFile("C:\Users\John\Desktop\Hydrofoil.Bmp"))
            RichTextBox1.Paste()
        End Sub
    
        Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RichTextBox1.MouseDown
            If e.Button = Windows.Forms.MouseButtons.Left Then
                If RichTextBox1.SelectionType = RichTextBoxSelectionTypes.Object And RichTextBox1.SelectedRtf.Contains("\pict\wmetafile8\") Then
                    Dim Temp As String = RichTextBox1.SelectedRtf.ToString
                    Dim TempR As Integer = 0
                    Dim Count As Integer = 0
                    For i = 0 To Temp.Count - 1
                        If Temp(i) = ChrW(10) Then
                            Count += 1
                            If Count = 2 Then
                                TempR = i
                                Exit For
                            End If
                        End If
                    Next
                    Temp = Temp.Remove(TempR, Temp.Count - TempR)
                    RTBMetaInfo.Add(Temp)
                    If My.Computer.FileSystem.FileExists("C:\Users\John\Desktop\RTBMetaInfo.Txt") Then
                        My.Computer.FileSystem.DeleteFile("C:\Users\John\Desktop\RTBMetaInfo.Txt")
                    End If
                    For Each Item In RTBMetaInfo
                        My.Computer.FileSystem.WriteAllText("C:\Users\John\Desktop\RTBMetaInfo.Txt", Item & vbCrLf, True)
                    Next
                End If
            End If
    
            If e.Button = Windows.Forms.MouseButtons.Right Then
                If RichTextBox1.SelectionType = RichTextBoxSelectionTypes.Object And RichTextBox1.SelectedRtf.Contains("\pict\wmetafile8\") Then
                    If MessageBox.Show("Do you want to convert this image?", "Convert Image", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then
                        SendMessage(RichTextBox1.Handle, WM_COPY, IntPtr.Zero, IntPtr.Zero)
    
                        Label1.Text = "Image properties before resize were" & vbCrLf & RTBMetaInfo(0)
                        Label2.Text = "Image properties after resize are" & vbCrLf & RTBMetaInfo(RTBMetaInfo.Count - 1)
                        Dim Temp1Split() As String = RTBMetaInfo(0).Split("\"c)
                        Dim Temp2Split() As String = RTBMetaInfo(RTBMetaInfo.Count - 1).Split("\"c)
                        Dim Temp1 As String = Temp1Split(Temp1Split.Count - 2) & "^" & Temp1Split(Temp1Split.Count - 1) & "^" & Temp2Split(Temp2Split.Count - 2) & "^" & Temp2Split(Temp2Split.Count - 1)
                        Temp1 = Temp1.Replace("picwgoal", "")
                        Temp1 = Temp1.Replace("pichgoal", "")
                        Dim Temp3Split() As String = Temp1.Split("^"c)
                        Dim Width1 As Integer = CInt(Temp3Split(0))
                        Dim Width2 As Integer = CInt(Temp3Split(2))
                        Dim Height1 As Integer = CInt(Temp3Split(1))
                        Dim Height2 As Integer = CInt(Temp3Split(3))
                        Dim Width3 As Integer = CInt((100 / Width1) * Width2)
                        Dim Height3 As Integer = CInt((100 / Height1) * Height2)
    
                        Label3.Text = "Original width and height were " & Width1.ToString & "  " & Height1.ToString & vbCrLf & _
                            "and resized width and height are " & Width2.ToString & "  " & Height2.ToString & vbCrLf & _
                            "so the new sizes width is approximately " & Width3.ToString & "% of the original width" & vbCrLf & _
                            "and the new sizes height is approximately " & Height3.ToString & "% of the original height."
    
                        Dim Img As New Bitmap(Clipboard.GetImage)
                        Dim newImage As Image = New Bitmap(CInt((Clipboard.GetImage.Width / 100) * Width3), CInt((Clipboard.GetImage.Height / 100) * Height3))
                        Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
                            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
                            graphicsHandle.DrawImage(Img, 0, 0, CInt((Clipboard.GetImage.Width / 100) * Width3), CInt((Clipboard.GetImage.Height / 100) * Height3))
                        End Using
                        PictureBox1.Width = newImage.Width
                        PictureBox1.Height = newImage.Height
                        PictureBox1.Image = newImage
                        Img.Dispose()
                        SendKeys.Send("{Delete}")
                        Clipboard.SetImage(PictureBox1.Image)
                        RichTextBox1.Paste()
                        RTBMetaInfo.Clear()
                    Else
                        RTBMetaInfo.Clear()
                    End If
                End If
            End If
        End Sub
    
    End Class



    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.


    Sunday, January 19, 2014 7:39 PM
  • "I know you ended this thread but I said I would post the code for my solution even if you found another solution."

    If you change the size of the displayed image instead of resizing the image, your solution should work the same as the accepted solution for Windows 3.1 and later.  Particularly, it should work like Word.


    • Edited by JohnWein Sunday, January 19, 2014 7:52 PM
    Sunday, January 19, 2014 7:49 PM
  • "I know you ended this thread but I said I would post the code for my solution even if you found another solution."

    If you change the size of the displayed image instead of resizing the image, your solution should work the same as the accepted solution for Windows 3.1 and later.  Particularly, it should work like Word.


    O.K. I did this so I could resize the image to know what size I wanted it to be before providing a resized quality image of it. Since I've no idea ahead of time what size I want the displayed image to be until after I resize it.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Sunday, January 19, 2014 9:28 PM
  • "O.K. I did this so I could resize the image to know what size I wanted it to be before providing a resized quality image of it. Since I've no idea ahead of time what size I want the displayed image to be until after I resize it."

    Why don't you want to change the size of the displayed image instead of the original pasted image?  How do you know the size of the resized image?  It looks like you resize the  displayed image with grab handles and then resize the original image to match the displayed image.  This will always reduce the possible quality to be obtained.

    Sunday, January 19, 2014 9:44 PM
  • "O.K. I did this so I could resize the image to know what size I wanted it to be before providing a resized quality image of it. Since I've no idea ahead of time what size I want the displayed image to be until after I resize it."

    Why don't you want to change the size of the displayed image instead of the original pasted image?  How do you know the size of the resized image?  It looks like you resize the  displayed image with grab handles and then resize the original image to match the displayed image.  This will always reduce the possible quality to be obtained.

    The original pasted image is the displayed image. I don't see any loss. I do see a good quality image replaced the RichTextBoxs resized image with an image of the same size basically. And since I resized the image in the RTB that's what size I want the good quality image that replaces it. I don't want to have to know ahead of time what size I want the image to be as I don't have ESP to know if it will be the correct size for where it is placed in the RTB.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.




    Sunday, January 19, 2014 10:26 PM
  • "The original pasted image is the displayed image."  No.  The RTF you posted is the RTF of a metafilepict which shows the size of the original image and the displayed image.  Try changing the size of the displayed image.  Use TwipsPerPixel.
    Sunday, January 19, 2014 11:03 PM
  • "The original pasted image is the displayed image."  No.  The RTF you posted is the RTF of a metafilepict which shows the size of the original image and the displayed image.  Try changing the size of the displayed image.  Use TwipsPerPixel.

    So pasting an image from the clipboard into paint is actually not pasting an image into paint but pasting a metafilepict into paint?

    Or copying an image from an RTB to the clipboard is actually copying a metafilepict to the clipboard and not an image?


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.

    Sunday, January 19, 2014 11:08 PM
  • "So pasting an image from the clipboard into paint is actually not pasting an image into paint but pasting a metafilepict into paint?

    Or copying an image from an RTB to the clipboard is actually copying a metafilepict to the clipboard and not an image?"

    Now you're getting stupid.

    RTF is text based.  Most images are binary arrays.

    Don't you see the dimensions of two images in the RTF you posted.  One is the original size and the other is the displayed size.  Change the displayed size.

    Sunday, January 19, 2014 11:16 PM
  • "So pasting an image from the clipboard into paint is actually not pasting an image into paint but pasting a metafilepict into paint?

    Or copying an image from an RTB to the clipboard is actually copying a metafilepict to the clipboard and not an image?"

    Now you're getting stupid.

    RTF is text based.  Most images are binary arrays.

    Don't you see the dimensions of two images in the RTF you posted.  One is the original size and the other is the displayed size.  Change the displayed size.

    Ummmm. Okay. I guess the RTBs resize of the image which created the posted RTF doesn't do that.


    Please BEWARE that I have NO EXPERIENCE and NO EXPERTISE and probably onset of DEMENTIA which may affect my answers! Also, I've been told by an expert, that when you post an image it clutters up the thread and mysteriously, over time, the link to the image will somehow become "unstable" or something to that effect. :) I can only surmise that is due to Global Warming of the threads.


    Sunday, January 19, 2014 11:27 PM