Converting DICOM image to jpeg image - java

My code is
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class DicomToJpeg {
public static void main(String args[]) throws IOException, Exception
{
dicomToJpeg("d:/F74AFBC7");
}
public static void dicomToJpeg(String args) throws IOException, Exception {
// TODO Auto-generated method stub
try
{
File myDicomFile = new File(args);
BufferedImage myJpegImage = null;
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
DicomImageReadParam param = null;
try{
param = (DicomImageReadParam) reader.getDefaultReadParam();
}
catch (Exception e) {
e.printStackTrace();
}
ImageInputStream iis=ImageIO.createImageInputStream(myDicomFile);
reader.setInput(iis, false);
myJpegImage = reader.read(0, param);
iis.close();
if (myJpegImage == null) {
System.out.println("\nError: couldn't read dicom image!");
return;
}
File myJpegFile = new File("d:/demo.jpg");
OutputStream output = new BufferedOutputStream(new FileOutputStream(myJpegFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(myJpegImage);
System.out.println("Image Create successufully");
output.close();
}
catch(IOException e){
System.out.println("\nError: couldn't read dicom image!"+ e.getMessage());
return;
}
}
}
When i execute in java project using eclipse it work fine...
But when i execute using web application and in this i call it from controller page like
DicomToJpeg.dicomToJpeg("d:/F74AFBC7");
then it gives error like...
java.util.NoSuchElementException
at javax.imageio.spi.FilterIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at com.lifecare.controller.DicomToJpeg.dicomToJpeg(DicomToJpeg.java:32)
How to solve this error please help me....

The javadoc to ImageIO.getImageREadersByFormatName says:
Returns an Iterator containing all currently registered ImageReaders
that claim to be able to decode the named format.
If you access the iterator without checking if it has an element, you will get an exception.
Since it runs in you IDE and not on the server, you may have a look if the image readers for the DICOM is in the application's classpath on the server.
However, I would also like to know how do you call the above class. Is it from a servlet?

I solved it by calling ImageIO.scanForPlugins() before ImageIO.getImageReadersByFormatName()
ImageIO.scanForPlugins()
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
This works perfectly on servlets

Try like this
BufferImage bi = ImageIO.read(dcm file name with path);
ImageIO.write(enter pathname with filename, format);

Related

Huge white space after header in PDF using Flying Saucer

I am trying to export an HTML page into a PDF using Flying Saucer. For some reason, the pages have a large white space after the header (id = "divTemplateHeaderPage1") divisions.
The jsFiddle link to my HTML code that is being used by PDF renderer: https://jsfiddle.net/Sparks245/uhxqdta6/.
Below is the Java code used for rendering the PDF (Test.html is the same HTML code in the fiddle) and rendering only one page.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.HTTP;
import org.json.JSONException;
import org.json.*;
import org.json.simple.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.*;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
import com.lowagie.text.List;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
#WebServlet("/PLPDFExport")
public class PLPDFExport extends HttpServlet
{
//Option for Serialization
private static final long serialVersionUID = 1L;
public PLPDFExport()
{
super();
}
//Get method
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
}
//Post method
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,
IOException
{
StringBuffer jb = new StringBuffer();
String line = null;
int Pages;
String[] newArray = null;
try
{
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
{ jb.append(line);
}
} catch (Exception e) { /*report an error*/ }
try
{
JSONObject obj = new JSONObject(jb.toString());
Pages = obj.getInt("Pages");
newArray = new String[1];
for(int cnt = 1; cnt <= 1; cnt++)
{
StringBuffer buf = new StringBuffer();
String base = "C:/Users/Sparks/Desktop/";
buf.append(readFile(base + "Test.html"));
newArray[0] = buf.toString();
}
}
catch (JSONException e)
{
// crash and burn
throw new IOException("Error parsing JSON request string");
}
//Get the parameters
OutputStream os = null;
try {
final File outputFile = File.createTempFile("FlyingSacuer.PDFRenderToMultiplePages", ".pdf");
os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
// we need to create the target PDF
// we'll create one page per input string, but we call layout for the first
renderer.setScaleToFit(true);
renderer.isScaleToFit();
renderer.setDocumentFromString(newArray[0]);
renderer.layout();
try {
renderer.createPDF(os, false);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// each page after the first we add using layout() followed by writeNextDocument()
for (int i = 1; i < newArray.length; i++) {
renderer.setScaleToFit(true);
renderer.isScaleToFit();
renderer.setDocumentFromString(newArray[i]);
renderer.layout();
try {
renderer.writeNextDocument();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// complete the PDF
renderer.finishPDF();
System.out.println("PDF Downloaded to " + outputFile );
System.out.println(newArray[0]);
}
finally {
if (os != null) {
try {
os.close();
} catch (IOException e) { /*ignore*/ }
}
}
//Return
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("File Uploaded");
}
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
}
The link for exported PDF: https://drive.google.com/file/d/13CmlJK0ZDLolt7C3yLN2k4uJqV3TX-4B/view?usp=sharing
I tried adding css properties like page-break-inside: avoid to the header divisions but it didn't work. Also I tried adding absolute positions and top margins to the body division (id = "divTemplateBodyPage1") just below the header div, but the white space continues to exist.
Any suggestions would be helpful.
Please take a look at the metadata of your PDF:
You are using an old third party tool that is not endorsed by iText Group, and that uses iText 2.1.7, a version of iText dating from 2009 that should no longer be used.
It would probably have been OK to complain and to write "My code isn't working" about 7 years ago, but if you would use the most recent version of iText, the result of converting your HTML to PDF would look like this:
I only needed a single line of code to get this result:
HtmlConverter.convertToPdf(new File(src), new File(dest));
In this line src is the path the the source HTML and dest is the path to the resulting PDF.
I only had to apply one minor change to your HTML. I change the #page properties like this:
#page {
size: 27cm 38cm;
margin: 0.2cm;
}
If I hadn't changed this part of the CSS, the page size would have been A4, and in that case, not all the content would have fitted the page. I also added a small margin because I didn't like the fact that the border was sticking to close to the sides of the page.
Morale: don't use old versions of libraries! Download the latest version of iText and the pdfHTML add-on. You need iText 7 core and the pdfHTML add-on. You might also want to read the HTML to PDF tutorial.

Update/Edit property file

I am testing a library (jar) that is using property (mytest.properties). They way the library (jar) loads the property is by doing
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
So what I want to test is what happens when the property file exist and when it does not exit. In order to test this I need to edit the property file once the JVM is started. I have tried doing that and does not work. Bellow is the code I tried to edit the property file but this always returns empty string.
Content of main_mytest.properties is:
a=hello world
b=hello java
Content of mytest.properties and empty.txt is empty.
""
My Class is:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class MyPropertyFiles {
final static String resourcesPath = "./mytestproj/src/main/resources";
public static void main(String [] args) throws IOException {
Path source = Paths.get(resourcesPath + "/main_mytest.properties");
Path destination = Paths.get(resourcesPath + "/mytest.properties");
Path empty = Paths.get(resourcesPath + "/empty.txt");
try
{
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "utf-8");
String theString = writer.toString();
System.out.println("!!!!!!!!!!!!!!!! The String: \n" + theString);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
Files.copy(empty, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
}
After doing some digging I don't think reloading the files in the ClassLoader after the JVM has started is allowed.

Determine image extension [duplicate]

This question already has answers here:
How to extract file extension from byte array
(3 answers)
Closed 7 years ago.
I am developing a web app, which has the functionality of displaying images obtained from a server. I learned that I can do it by returning byte array in response.
It seems that I am able to do it through:
#RequestMapping(value = "url/img", method = RequestMethod.POST)
#ResponseBody
public MyDto proceedDocumentFromUrl(#RequestParam final String url) throws IOException {
return somethingDoer.do(toByteArray(new URL(url).openStream());
}
somethingDoer.do returns Dto object which contains byte[] In field named image. For test purposes I would like to determine the image extension (it is always .jpg).
How can I do that? I was looking in Wiki and W3 documents for some clue(I suppose it is about first few bytes) but was unable to find a solution.
Please check this getFormatName(file) method and check Class ImageReader
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("image.gif");
System.out.println(getFormatName(file));
InputStream is = new FileInputStream(file);
is.close();
System.out.println(getFormatName(is));
}
private static String getFormatName(Object o) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(o);
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader) iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
}
return null;
}
}
Please check https://github.com/arimus/jmimemagic to get extension from byte[]
byte[] data = someData
MagicMatch match = Magic.getMagicMatch(data);
System.out.println( match.getMimeType());

Exception in thread "main" java.lang.IllegalAccessError: [duplicate]

This question already has an answer here:
Apache POI Parsing error
(1 answer)
Closed 7 years ago.
I am getting the below Exception when I am trying to read an Excel file:
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class org.apache.poi.openxml4j.opc.PackageRelationshipCollection
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:304)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:156)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:124)
at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:559)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:112)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:83)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:128)
at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78)
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:218)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:223)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:186)
at readAndWriteToExcel.ReadingExcel.main(ReadingExcel.java:36)
My code is:
package readAndWriteToExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
public class ReadingExcel {
private static final Log LOG = LogFactory
.getLog(ReadingExcel.class);
public static void main(String[] args) throws Exception {
String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/Documents/Test Data 5.xlsx";
File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
InputStream inputStream = new FileInputStream(file);
// The package open is instantaneous, as it should be.
OPCPackage pkg = null;
try {
ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler = new ExcelWorkSheetRowCallbackHandler(
new ExcelRowContentCallback() {
public void processRow(int rowNum, Map<String, String> map) {
// Do any custom row processing here, such as save
// to database
// Convert map values, as necessary, to dates or
// parse as currency, etc
System.out.println("rowNum=" + rowNum + ", map=" + map);
}
});
pkg = OPCPackage.open(inputStream);
ExcelSheetCallBack sheetCallback = new ExcelSheetCallBack() {
private int sheetNumber = 0;
public void startSheet(int sheetNum) {
this.sheetNumber = sheetNum;
System.out.println("Started processing sheet number=" + sheetNumber);
}
public void endSheet() {
System.out.println("Processing completed for sheet number=" + sheetNumber);
}
};
System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
ExcelReader example1 = new ExcelReader(pkg,
sheetRowCallbackHandler, sheetCallback);
example1.process();
System.out.println("nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler, sheetCallback);
example2.process();
System.out.println("nConstructor: file, sheetRowCallbackHandler, sheetCallback");
ExcelReader example3 = new ExcelReader(file,
sheetRowCallbackHandler, null);
example3.process();
} catch (RuntimeException are) {
LOG.error(are.getMessage(), are.getCause());
} catch (InvalidFormatException ife) {
LOG.error(ife.getMessage(), ife.getCause());
} catch (IOException ioe) {
LOG.error(ioe.getMessage(), ioe.getCause());
} finally {
IOUtils.closeQuietly(inputStream);
try {
if (null != pkg) {
pkg.close();
}
} catch (IOException e) {
// just ignore IO exception
}
}
}
}
Is there a simple way to read and edit an Excel file (xls and xlsx) with more than 50k records? I have searched a lot and worked with a few available codes.
But I was not successful, I keep ending up with one Exception or another.
I was getting the same error:
"Handler processing failed; nested exception is
java.lang.IllegalAccessError: tried to access method
org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class
org.apache.poi.openxml4j.opc.PackageRelationshipCollection"
After updating maven and trying to access PackageRelationshipCollection and POILogger classes in eclipse things worked fine for me. Make sure you have all the required jars i.e poi, poi-ooxml, poi-ooxml-schemas.

How to render PNG image from DFX file by using kabeja package?

I'm new to this kabeja package so please can some one provide code example or reading material to render PNG from DXF file using Java?
This is the sample code that generate PNG image from DXF file.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.*;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.*;
public class MyClass {
public static void main(String[] args) {
MyClas x=new MyClas();
x.parseFile("C:\\Users\\Space\\Desktop\\test2.dxf");
}
public void parseFile(String sourceFile) {
try {
FileOutputStream o=new FileOutputStream("C:\\Users\\Space\\Desktop\\test2.png");
InputStream in = new FileInputStream(sourceFile);//your stream from upload or somewhere
Parser dxfParser = ParserBuilder.createDefaultParser();
dxfParser.parse(in, "");
DXFDocument doc = dxfParser.getDocument();
SVGGenerator generator = new SVGGenerator();
//org.xml.sax.InputSource out = SAXPNGSerializer;
SAXSerializer out = new org.kabeja.batik.tools.SAXPNGSerializer();
out.setOutput(o);
generator.generate(doc,out,new HashMap());
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
Hope you get what you required :)

Categories