2013-09-02 13 views
11

पर डेटा-यूआरएल कनवर्ट करें मेरे पास एक छवि फ़ाइल से डेटा-यूआरएल है और उसे किसी अन्य फ़ंक्शन के माध्यम से पास करना होगा। डेटा-यूआरएल से BufferedImage तक इस पथ के साथ इसे एक बाइटएरे होना चाहिए।BufferedImage

String dataUrl; 
byte[] imageData = dataUrl.getBytes(); 

// pass the byteArray along the path 

// create BufferedImage from byteArray 
BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(imageData)); 

// If the picture is null, then throw an unsupported image exception. 
if (inputImage == null) { 
    throw new UnknownImageFormatException(); 
} 

समस्या है, यह हमेशा UnknownImageFormatException अपवाद है, जिसका अर्थ inputImage रिक्त है, जिसका अर्थ है, ImageIO.read imagetype पहचाना नहीं फेंकता है:

मेरे दृष्टिकोण निम्नलिखित था।

मैं ImageIO.getReaderFormatNames का उपयोग किया है() समर्थित फ़ाइल नामों को मिलता है और निम्न सूची मिल करने के लिए: जहाँ तक data:image/png;base64,... या data:image/jpg;base64,...

:

Supported Formats: 
jpg, BMP, bmp, JPG, jpeg, wbmp, png, JPEG, PNG, WBMP, GIF, gif 

dataURLs मैं पारित करने के लिए कोशिश कर रहे हैं की तरह मैं समझता हूं, वे समर्थित फ़ाइललिस्ट में हैं और इसके लिए पहचाना जाना चाहिए।

इस मामले में इनपुट इमेज को और क्या कारण हो सकता है? और अधिक दिलचस्प, मैं इसे कैसे हल करूं?

+3

आपको स्ट्रिंग को बेस 64 से वापस एक बाइनरी प्रारूप में डीकोड करने की आवश्यकता है, जिसे इमेजियो पढ़ सकता है, या यदि आपके पास कोई यूआरएल ऑब्जेक्ट है, तो शायद इसे सीधे इमेजियो – MadProgrammer

+2

पर पास कर दें @MadProgrammer की सलाह के लिए आप [' डेटा 64 टाइप को वापस 'बाइट []' में परिवर्तित करने के लिए डेटाटाइप कनवर्टर'] (http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/DatatypeConverter.html#method_summary)। –

उत्तर

16

जैसा कि टिप्पणियों ने पहले ही कहा है कि छवि डेटा बेस 64 एन्कोडेड है। बाइनरी डेटा को पुनर्प्राप्त करने के लिए आपको टाइप/एन्कोडिंग हेडर को स्ट्रिप करना होगा, फिर बेस 64 सामग्री को बाइनरी डेटा में डीकोड करें।

String encodingPrefix = "base64,"; 
int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length(); 
byte[] imageData = Base64.decodeBase64(dataUrl.substring(contentStartIndex)); 

मैं अपाचे से org.apache.commons.codec.binary.Base64 का उपयोग आम कोडेक, अन्य Base64 डिकोडर के साथ-साथ काम करना चाहिए।

+5

जावा 8 के रूप में, मूल जेडीके में बेस 64 एन्कोडर/डिकोडर है: http://download.java.net/jdk8/docs/api/java/util/Base64.html – Jules

3

RFC2397 तार के साथ केवल एक ही समस्या डेटा से पहले सब कुछ के साथ अपने विनिर्देश लेकिन data: और , वैकल्पिक है:

data:[<mediatype>][;base64],<data> 

तो शुद्ध जावा 8 समाधान लेखांकन इस होगा:

final int dataStartIndex = dataUrl.indexOf(",") + 1; 
final String data = dataUrl.substring(dataStartIndex); 
byte[] decoded = java.util.Base64.getDecoder().decode(data); 
बेशक

डेटास्टार्ट इंडेक्स की जांच की जानी चाहिए।

संबंधित मुद्दे