`

Image to string and string to image conversion

阅读更多
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
 
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
 
import com.sun.org.apache.xml.internal.security.utils.Base64;
 
public class Utility
{
	//here path of image is needed to convert it into string
	public String ImageToString(String imagePath) throws Exception
	{
		File file = new File(imagePath);
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		try
		{
			for (int readNum; (readNum = fis.read(buffer)) != -1;)
			{
				baos.write(buffer, 0, readNum);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		byte[] bytes = baos.toByteArray();
		String imagestring = Base64.encode(bytes);
		return imagestring;
	}
	//here String is provided to be converted into given extension (image only)
	//image created on the fly is stored into pathToStore
	public void StringToImage(String imageContainer, String Extension,
			String pathToStore)
	{
 
		byte[] ImageByteArray;
		try
		{
			ImageByteArray = Base64.decode(imageContainer);
 
			ByteArrayInputStream bais = new ByteArrayInputStream(ImageByteArray);
			Iterator<?> readers = ImageIO
					.getImageReadersByFormatName(Extension);
 
			ImageReader reader = (ImageReader) readers.next();
			Object source = bais;
 
			ImageInputStream iis = ImageIO.createImageInputStream(source);
			reader.setInput(iis, true);
			ImageReadParam param = reader.getDefaultReadParam();
 
			Image image = reader.read(0, param);
 
			BufferedImage buffimage = new BufferedImage(image.getWidth(null),
					image.getHeight(null), BufferedImage.TYPE_INT_RGB);
 
			Graphics2D g2 = buffimage.createGraphics();
			g2.drawImage(image, null, null);
			File newfile = new File(pathToStore);
			ImageIO.write(buffimage, Extension, newfile);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
 
	}
	
	public static void main(String[] args) throws Exception
	{
		Utility ut = new Utility();

//		String str = ut.ImageToString("c:/ss.bmp");
//		File file = new File("c:/ss.txt");
//		FileOutputStream out = new FileOutputStream(file);
//		out.write(str.getBytes());
//		out.flush();
//		out.close();
		
		File file = new File("c:/ss.txt");
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		String line = null;
		StringBuffer all = new StringBuffer();
		while((line = in.readLine()) != null)
		{
			all.append(line);
		}
		
		ut.StringToImage(all.toString(), "BMP", "c:/ff.jpg");
	}
}
分享到:
评论

相关推荐

    TCL TK 语言8.5编程指导

    Parsing a string using conversion specifiers 47 Determining the length of a string 49 Comparing strings 50 Comparing a string of characters 51 Locating the first instance of a character 52 Locating ...

    Senfore_DragDrop_v4.1

    4) Add the Drag and Drop Component Suite components directory to your library path. 5) Load the demo project group: demo\dragdrop_delphi.bpg for Delphi 5 and 6 demo\dragdrop_bcb4.bpg for C++ ...

    使用GDI+进行图片格式转换

    Console.WriteLine("Image conversion successful."); } catch (Exception ex) { Console.WriteLine("Error converting image: " + ex.Message); } Console.ReadLine(); } ``` 这个测试程序从`.jpg`文件...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - ADD: Add TFlexPanel.InvalidateControl virtual method which calls from TFlexControl.Invalidate and can be overriden (it is possible now to catch all object invalidation calls). - FIX: The TFlexPanel....

    WPTools.v6.29.1.Pro

    * HTML reader sets image width and height to contents, (if possible) * HTML reader: changes UTF8 handling for UTF8Sequence=1 * HTML reader does not stop on \0 anymore * ...

    VB编程资源大全(英文源码 其它)

    specify how you want it to look and will create the source code for you and put it into the clipboard where you &lt;END&gt;&lt;br&gt;47,vb2word.zip This program builds a Hex-Decimal-Binary conversion table ...

    雷达技术知识

    LiDAR Data and Image Acquisition 23 Field Data Acquisition 24 LiDAR Processing 25 Calculation of Water Surface Slopes 27 Evaluating LiDAR Slope Accuracies and Controls 33 V. RESULTS 35 Comparison of ...

    Jpeg转PDF的java代码实现

    System.out.println("JPEG to PDF conversion successful."); } catch (IOException e) { System.err.println("Error converting JPEG to PDF: " + e.getMessage()); } } } ``` 这段代码首先创建了一个`...

    TMS Pack for FireMonkey2.3.0.1

    Improved : Escape to cancel date selection and return to previous selected date in TTMSFMXCalendar Fixed: Issue with autosizing and client-aligned captions v2.0.1.0 New : Pointer direction ...

    Convert WebP to PNG using java

    System.out.println("WebP to PNG conversion successful."); } catch (Exception e) { System.err.println("Error converting WebP to PNG: " + e.getMessage()); } } } ``` 这段代码展示了如何使用`ImageIO....

    轻松使用apache pdfbox将pdf文件生成图片.docx

    在处理 PDF 到图片的转换时,PDFBox 提供了 PDPage 类的 convertToImage() 方法,这个方法能够将 PDF 的单页转换为 BufferedImage 对象,这是一个 Java 中的图像类,可以进一步保存为各种格式的图片,如 JPG、PNG 等...

    ZendFramework中文文档

    StringTrim 14.2.12. StripTags 14.3. 过滤器链 14.4. 编写过滤器 14.5. Zend_Filter_Input 14.5.1. Declaring Filter and Validator Rules 14.5.2. Creating the Filter and Validator Processor 14.5.3. ...

    oracle函数大全.doc

    SQL&gt; select convert('strutz','we8hp','f7dec') "conversion" from dual; conver ------ strutz 44.HEXTORAW 将一个十六进制构成的字符串转换为二进制 45.RAWTOHEXT 将一个二进制构成的字符串转换为十六进制 46....

    LeetCode最全代码

    * [String](https://github.com/kamyu104/LeetCode#string) * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue]...

    unigui0.83.5.820

    - 0000689: CustomFiles property for ServerModule to add custom CSS and JS files - 0000688: Bug in installer Environment setter - 0000687: "Script" property for TUniForm for adding Custom JS - 0000665...

    MYSQL,SQLSERVER,ORACLE常用的函数

    TO_DATE(string, 'format') 将字符串转换为日期类型。例如: ```sql SELECT TO_DATE('2023-03-05', 'yyyy-mm-dd') FROM dual; ``` 输出结果为日期值。 #### 48. TO_MULTI_BYTE 将单字节字符转换为多字节字符。例如...

    leetcode跳跃-leetcode:leetcode解题之路

    leetcode 跳跃 leetcode 按题型标签,记录leetcode 解题之路 Stack 栈 [0020 有效的括号](./Stack/valid-parentheses.md) ...Z字形变换](./String/zigzag-conversion.md) [0030 串联所有单词的子串](./String/substring

    Oracle函数大全

    SQL&gt; INSERT INTO file_tb1 VALUES (BFILENAME('lob_dir1', 'image1.gif')); ``` ### 10. CEIL - 返回大于或等于给出数字的最小整数 - **语法**: `CEIL(number)` - **参数**: - `number`: 需要向上取整的数值。...

    ZJU_ACM_All_Anwer 搞编程的都知道的浙江大学A 题库.本书 集了所有经 Z 题解集,集合并附 Mathimaticsumerical algorithms 数值算法

    1459 String Distance and Transform Process 简单题 1462 Team Them Up! 简单题 1556 Heroes Of Might And Magic 简单题,不过背景蛮有意思的…… 1520 Duty Free Shop 简单题 1524 Supermarket 简单题 ...

Global site tag (gtag.js) - Google Analytics