Click here to Skip to main content
15,888,968 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
please Help..


Thanks in advance.

What I have tried:

i don't know how to convert CroppedBitmap to BitmapImage
Posted
Updated 16-Aug-17 3:16am

1 solution

If you look at the answer to the previous question that you asked: HOW to crop image in WPF VB[^], you would have seen this line:
C#
var img = image1.Source as BitmapSource;

and then this:
C#
image2.Source = new CroppedBitmap(inputImage, rcFrom);

and according to Microsoft documentation[^], also linked in the previous question's answers, has the following comment:
Quote:
The following example creates an image using a CroppedBitmap as its source.

Therefore, CroppedBitmap actually returns a bitmapped object of BitmapSource type which has more information that you are asking for in the question above: BitmapSource Class - Microsoft documentation[^] with examples.

UPDATE #1

Expanding on above (CroppedBitmap.Source returns a BitmapSource type), and using the solution to your previous question, along with a google search & using the found article c# - BitmapSource to BitmapImage - Stack Overflow[^], the answer was there if you did a little work, like I just did.

Here is a working solution that gives you the choice of image encoding (Jpg or Png):
C#
private void Go_Click(object sender, RoutedEventArgs e)
{
    if (image1.Source != null)
    {
        var rect1 = new Rect()
        {
            X = Canvas.GetLeft(selectionRectangle),
            Y = Canvas.GetTop(selectionRectangle),
            Width = selectionRectangle.Width,
            Height = selectionRectangle.Height
        };

        // calc scale in PIXEls for CroppedBitmap...
        var img = image1.Source as BitmapSource;
        var scaleWidth = (img.PixelWidth) / (image1.ActualWidth);
        var scaleHeight = (img.PixelHeight) / (image1.ActualHeight);

        var rcFrom = new Int32Rect()
        {
            X = (int)(rect1.X * scaleWidth),
            Y = (int)(rect1.Y * scaleHeight),
            Width = (int)(rect1.Width * scaleWidth),
            Height = (int)(rect1.Height * scaleHeight)
        };

        var cropped = new CroppedBitmap(inputImage, rcFrom);

        // UPDATE HERE: CroppedBitmap to BitmapImage
        croppedImage = GetJpgImage(cropped.Source);
        // or 
        // croppedImage = GetPngImage(cropped.Source);

        // using BitmapImage version to prove its created successfully
        image2.Source = croppedImage; //cropped;
    }
}

private BitmapImage croppedImage;

private BitmapImage GetJpgImage(BitmapSource source)
{
    return GetImage(source, new JpegBitmapEncoder());
}

private BitmapImage GetPngImage(BitmapSource source)
{
    return GetImage(source, new PngBitmapEncoder());
}

private BitmapImage GetImage(BitmapSource source, BitmapEncoder encoder)
{
    var bmpImage = new BitmapImage();

    using (var srcMS = new MemoryStream())
    {
        encoder.Frames.Add(BitmapFrame.Create(source));
        encoder.Save(srcMS);

        srcMS.Position = 0;
        using (var destMS = new MemoryStream(srcMS.ToArray()))
        {
            bmpImage.BeginInit();
            bmpImage.StreamSource = destMS;
            bmpImage.CacheOption = BitmapCacheOption.OnLoad;
            bmpImage.EndInit();
            bmpImage.Freeze();
        }
    }

    return bmpImage;
}


UPDATE #2 As mentioned below, here is how to save...
C#
private void Save_Click(object sender, RoutedEventArgs e)
{
    // save to current working directory
    SaveJpgImage(croppedImage, @".\cropped.jpg");

}

private void SaveJpgImage(BitmapImage source, string photoLocation)
{
    SaveImage(source, photoLocation, new JpegBitmapEncoder());
}

private void SavePngImage(BitmapImage source, string photoLocation)
{
    SaveImage(source, photoLocation, new PngBitmapEncoder());
}

private void SaveImage(BitmapImage source, string photoLocation, BitmapEncoder encoder)
{
    encoder.Frames.Add(BitmapFrame.Create(source));

    using (var filestream = new FileStream(photoLocation, FileMode.Create))
        encoder.Save(filestream);
}


UPDATE #3

Just noticed the VB tag - sorry about that... VB version below...
VB
Imports System.IO

Class MainWindow

    Private isDragging As Boolean
    Private anchorPoint As New Point()

    Public Sub New()

        InitializeComponent()

        inputImage = New BitmapImage(New Uri("pack://application:,,,/Images/Code Project Sample_300 dpi.JPEG"))
        'inputImage = new BitmapImage(new Uri("http://eskipaper.com/images/cool-morning-fog-wallpaper-1.jpg"));
        image1.Source = inputImage

        Go.IsEnabled = False
        image2.Source = Nothing

    End Sub

    Private ReadOnly Property inputImage As BitmapImage

    Private Sub Go_Click(sender As Object, e As RoutedEventArgs)

        If image1.Source IsNot Nothing Then

            Dim rect1 = New Rect() With {
                    .X = Canvas.GetLeft(selectionRectangle),
                    .Y = Canvas.GetTop(selectionRectangle),
                    .Width = selectionRectangle.Width,
                    .Height = selectionRectangle.Height
                }

            ' calc scale in PIXEls for CroppedBitmap...
            Dim img = TryCast(image1.Source, BitmapSource)
            Dim scaleWidth = (img.PixelWidth) / (image1.ActualWidth)
            Dim scaleHeight = (img.PixelHeight) / (image1.ActualHeight)

            Dim rcFrom = New Int32Rect() With {
                    .X = CInt(rect1.X * scaleWidth),
                    .Y = CInt(rect1.Y * scaleHeight),
                    .Width = CInt(rect1.Width * scaleWidth),
                    .Height = CInt(rect1.Height * scaleHeight)
                }

            Dim cropped = New CroppedBitmap(inputImage, rcFrom)
            croppedImage = GetJpgImage(cropped)

            ' using BitmapImage version to prove its created successfully
            image2.Source = croppedImage 'cropped

        End If

    End Sub

    Private croppedImage As BitmapImage

    Private Function GetJpgImage(source As BitmapSource) As BitmapImage

        Return GetImage(source, New JpegBitmapEncoder())

    End Function

    Private Function GetPngImage(source As BitmapSource) As BitmapImage

        Return GetImage(source, New PngBitmapEncoder())

    End Function

    Private Function GetImage(source As BitmapSource, encoder As BitmapEncoder) As BitmapImage

        Dim bmpImage = New BitmapImage()

        Using srcMS = New MemoryStream()

            encoder.Frames.Add(BitmapFrame.Create(source))
            encoder.Save(srcMS)

            srcMS.Position = 0
            Using destMS = New MemoryStream(srcMS.ToArray())
                bmpImage.BeginInit()
                bmpImage.StreamSource = destMS
                bmpImage.CacheOption = BitmapCacheOption.OnLoad
                bmpImage.EndInit()
                bmpImage.Freeze()
            End Using

        End Using

        Return bmpImage

    End Function

#Region "Mouse events"
     Private Sub image1_MouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)

        If Not isDragging Then
            anchorPoint.X = e.GetPosition(BackPanel).X
            anchorPoint.Y = e.GetPosition(BackPanel).Y
            isDragging = True
        End If

    End Sub

    Private Sub image1_MouseMove(sender As Object, e As MouseEventArgs)

        If isDragging Then

            Dim x As Double = e.GetPosition(BackPanel).X
            Dim y As Double = e.GetPosition(BackPanel).Y

            selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X))
            selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y))
            selectionRectangle.Width = Math.Abs(x - anchorPoint.X)
            selectionRectangle.Height = Math.Abs(y - anchorPoint.Y)

            If selectionRectangle.Visibility <> Visibility.Visible Then
                selectionRectangle.Visibility = Visibility.Visible
            End If

        End If

    End Sub

    Private Sub image1_MouseLeftButtonUp(sender As Object, e As MouseButtonEventArgs)

        If isDragging Then

            isDragging = False

            If selectionRectangle.Width > 0 Then
                Go.Visibility = Visibility.Visible
                Go.IsEnabled = True
            End If

            If selectionRectangle.Visibility <> Visibility.Visible Then
                selectionRectangle.Visibility = Visibility.Visible
            End If

        End If

    End Sub

    Private Sub RestRect()

        selectionRectangle.Visibility = Visibility.Collapsed
        isDragging = False

    End Sub

#End Region

    Private Sub Save_Click(sender As Object, e As RoutedEventArgs)

        ' save to current working directory
        SaveJpgImage(croppedImage, ".\cropped.jpg")

    End Sub

    Private Sub SaveJpgImage(source As BitmapImage, photoLocation As String)

        SaveImage(source, photoLocation, New JpegBitmapEncoder())

    End Sub

    Private Sub SavePngImage(source As BitmapImage, photoLocation As String)

        SaveImage(source, photoLocation, New PngBitmapEncoder())

    End Sub

    Private Sub SaveImage(source As BitmapImage, photoLocation As String, encoder As BitmapEncoder)

        encoder.Frames.Add(BitmapFrame.Create(source))

        Using filestream = New FileStream(photoLocation, FileMode.Create)
            encoder.Save(filestream)
        End Using

    End Sub

End Class
 
Share this answer
 
v5
Comments
ketan Ram Patil 17-Aug-17 1:51am    
:(
first i am converting the CroppedBitmap to bitmapsource and then bitmapsource to bitmap and then bitmap to bitmapimage it converts successfully.

but when i am converting bitmapimage to byte it gives error

Unable to cast object of type 'System.Windows.Media.Imaging.CroppedBitmap' to type 'System.Windows.Media.Imaging.BitmapImage'.
ketan Ram Patil 17-Aug-17 8:59am    
thank you for your valuable replay.. :)

in above code the cropped object passes croppedbitmap to image2 source. i want to pass only bitmapimage.

when i am passsing croppedImage object to image2 source it displays blank image.:(
Graeme_Grant 17-Aug-17 9:47am    
As it turns out I missed one step with the creation of the BitmapImage - I needed to set the CacheOption property. I'll update the solution + I have added save to file which, no doubt, will be your next question.
ketan Ram Patil 18-Aug-17 0:36am    
n again thank you.. :)
have a great day... :)
It works perfectly.
Graeme_Grant 18-Aug-17 2:32am    
You are welcome. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900