Save image using callBack function in C# and .NET


Modern programming often requires processing and converting various types of data, including documents, images, and their integration into web applications. This is especially true when working with rich text formats (RTF), which can contain not only text but also graphic elements. In this article, we'll discuss how to implement image saving using the CallBack function in C# and .NET, using the component RTF TO HTML .NET from SautinSoft SDK.

CallBack is a callback mechanism that allows you to provide a custom function called within a process or library method. When processing documents or converting RTF to HTML, CallBack allows you to intervene in the conversion process, for example, by replacing or preserving images found in the source documents.

CallBack is especially effective when you need to dynamically manage content, control processing, or save embedded resources outside of standard library methods.

Key benefits of using CallBack for image saving:

  1. Flexibility and control: You have complete control over the image saving process, defining their format, file name, location, and even modifying their content before saving.
  2. Automation: By automatically processing embedded images, you can integrate saving into more complex business processes or content management systems.
  3. Storage optimization: You can implement automatic image compression, format changes, minimizing file size, or improving compatibility.
  4. Extensibility: Integrate with your own storage systems, such as uploading images to the cloud or database.

Practical use cases include:

  • Legal document processing: Automatically export images contained in RTF for archiving or further processing.
  • Content management systems: Automatically extract images from a document for subsequent editing or publishing.
  • HTML reporting: Convert complex reports with graphics to HTML while preserving the visual component.
  • Email processing: Extract image attachments from RTF messages for analysis or display.

Input file:

rtf to html input

Output result (html):

ImagesSavingCallback html output

Output result (images):

ImagesSavingCallback output

Complete code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SautinSoft;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            UsingImagesSavingCallback();
        }
        /// <summary>
        /// How to use image saving callback and set a template name for all images.
        /// </summary>
        static void UsingImagesSavingCallback()
        {
			// Get your free key here:   
            // https://sautinsoft.com/start-for-free/
			
            // If you need more information about "RTF to HTML .Net" 
            // Email us at: support@sautinsoft.com.
			
            string inpFile = @"..\..\..\example.docx";
            string outFile = Path.GetFullPath(@"Result.html");
            string imgDir = Path.GetDirectoryName(outFile);

            RtfToHtml r = new RtfToHtml();

            // Set images directory
            RtfToHtml.HtmlFixedSaveOptions opt = new RtfToHtml.HtmlFixedSaveOptions()
            {
                ImagesDirectoryPath = Path.Combine(imgDir, "Result_images"),
                ImagesDirectorySrcPath = "Result_images",
                // Change to store images as physical files on local drive.
                EmbedImages = false,
                ImageSavingCallback = new SaveImagesOpt() { TemplateImageName = "MyPicture"}
            };

            try
            {
                r.Convert(inpFile, outFile, opt);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Conversion failed! {ex.Message}");
            }

            // Open the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
    public class SaveImagesOpt : RtfToHtml.IHtmlImageSavingCallback
    {
        public string TemplateImageName { get; set; } = "picture";
        public void ImageSaving(RtfToHtml.HtmlImageSavingArgs args)
        {
            args.ImageFileName = args.ImageFileName.Replace("image", TemplateImageName);
        }
    }
}

Download

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Imports SautinSoft

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			ImagesCallback()
		End Sub
		''' <summary>
		''' How to use image saving callback and set a template name for all images.
		''' </summary>
		Private Shared Sub ImagesCallback()
				    ' Get your free key here:   
            ' https://sautinsoft.com/start-for-free/
			
            ' If you need more information about "RTF to HTML .Net" 
            ' Email us at: support@sautinsoft.com.
			Dim inpFile As String = "..\..\..\example.docx"
			Dim outFile As String = Path.GetFullPath("Result.html")
			Dim imgDir As String = Path.GetDirectoryName(outFile)

			Dim r As New RtfToHtml()

			' Set images directory
			Dim opt As new RtfToHtml.HtmlFixedSaveOptions() With {
				.ImagesDirectoryPath = Path.Combine(imgDir, "Result_images"),
				.ImagesDirectorySrcPath = "Result_images",
				.EmbedImages = False,
				.ImageSavingCallback = New SaveImagesOpt() With {.TemplateImageName = "MyPicture"}
			}

			Try
				r.Convert(inpFile, outFile, opt)
			Catch ex As Exception
				Console.WriteLine($"Conversion failed! {ex.Message}")
			End Try

			' Open the result.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
	Public Class SaveImagesOpt
		Implements RtfToHtml.IHtmlImageSavingCallback

		Public Property TemplateImageName() As String = "picture"

		Private Sub IHtmlImageSavingCallback_ImageSaving(args As RtfToHtml.HtmlImageSavingArgs) Implements RtfToHtml.IHtmlImageSavingCallback.ImageSaving
			args.ImageFileName = args.ImageFileName.Replace("image", TemplateImageName)
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:


Captcha

Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.