logo
down
shadow

sparkjava: Load PNG as base64 from InputStream


sparkjava: Load PNG as base64 from InputStream

By : Xiaoquan Wu
Date : November 21 2020, 11:01 PM
I wish this helpful for you After setting the MIME type in the header with response.header("Content-Type", "image/png") (look up your MIME type here), you can use this:
code :
try {
    return Files.readAllBytes(Paths.get(MyClass.class.getResource(path).toURI()));
} catch (IOException | URISyntaxException exception) {
    exception.printStackTrace();
}

return null;
Base64.getMimeEncoder().encodeToString(resourceAsString.getBytes(StandardCharsets.UTF_8))


Share : facebook icon twitter icon
Base64 InputStream to String

Base64 InputStream to String


By : Tchekov
Date : March 29 2020, 07:55 AM
Does that help I found the solution, inspired by this post getting base64 content string of an image from a mimepart in Java
I think it is kind of stupid decode and encode again the base64 code, but it is the only way I found to manage this issue. If someone could give a better solution, it would be also really appreciated.
How do you convert an InputStream to a base64 string in Scala?

How do you convert an InputStream to a base64 string in Scala?


By : Marcos Insfran
Date : March 29 2020, 07:55 AM
may help you . Trying to pull an image off of Amazon S3 (returns S3ObjectInputStream) and send it to the mandrill email api (takes a base64-encoded string). How can this be done in Scala? , Here is one solution, there are probably others more efficient.
code :
val is = new ByteArrayInputStream(Array[Byte](1, 2, 3)) // replace by your InputStream
val stream = Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte)
val bytes = stream.toArray
val b64 = new sun.misc.BASE64Encoder().encode(bytes)
val b64 = org.apache.commons.codec.binary.Base64.encodeBase64(bytes)
Compare a base64 image to InputStream

Compare a base64 image to InputStream


By : sidharth wadhwa
Date : March 29 2020, 07:55 AM
this one helps. Well, the images to our "eyes" are equal (well not exactly equal as you can see some foggy pixels) but Android internally does lower the image quality making it not match the original image. Therefore the unit test fails.
Remove Base64 prefix from InputStream

Remove Base64 prefix from InputStream


By : Ifelajulo Fasina
Date : March 29 2020, 07:55 AM
help you fix your problem
How do I remove the Base64 prefix from a Stream being sent to the client without storing and editing the entire Stream on the server?
code :
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
    br = new BufferedReader(new InputStreamReader(stream));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    String result = sb.toString();
    //comma is the charater which seperates the prefix and the Base64 String
    int i = result.indexOf(",");
    result = result.substring(i + 1);
    //Now, that we have just the Base64 encoded String, we can decode it
    Base64.Decoder decoder = Base64.getDecoder();
    byte[] decoded = decoder.decode(result);
    //Now, just write each byte from the byte array to the output stream
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
S3Object obj = s3Client.getObject(new GetObjectRequest(bucketName, keyName));
Base64.Decoder decoder = Base64.getDecoder();
InputStream stream = obj.getObjectContent();
InputStreamReader reader = new InputStreamReader(stream);
try{
    return new StreamingOutput(){
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException{
            //for checking if string has base64 prefix
            char[] pre = new char[4]; //"data" has at most four bytes on a UTF-8 encoding
            boolean containsPre = false;
            int count = 0;
            int nextByte = 0;
            while((nextByte = stream.read()) != -1){
                if(count < pre.length){
                    pre[count] = (char) nextByte;
                    count++;
                }else if(count == pre.length){
                    //determine whether has prefix or not and act accordingly
                    count++;
                    containsPre = (Arrays.toString(pre).toLowerCase().equals("data")) ? true : false;
                    if(!containsPre){
                        //doesn't have Base64 prefix so write all the bytes until this point
                        for(int i = 0; i < pre.length; i++){
                            output.write((int) pre[i]);
                        }
                        output.write(nextByte);
                    }
                }else if(containsPre && count < 25){
                    //the comma character (,) is considered the end of the Base64 prefix
                    //so look for the comma, but be realistic, if we don't find it at about 25 characters
                    //we can assume the String is not encoded correctly
                    containsPre = (Character.toString((char) nextByte).equals(",")) ? false : true;
                    count++;
                }else{
                    output.write(nextByte);
                }
            }
            output.flush();
            output.close();
            stream.close();
        }
    };
}catch(Exception e){
    e.printStackTrace();
    return null;
}
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
    br = new BufferedReader(new InputStreamReader(stream));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    return sb.toString();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
int i = result.indexOf(",");
result = result.substring(i + 1);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap bitMap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
How to get Base64 String from InputStream?

How to get Base64 String from InputStream?


By : Fab's
Date : March 29 2020, 07:55 AM
I wish this helpful for you I'm on a problem by taking the selected gallery picture and want to save it first as Base64 String in a XML file (for later use. For example if you exit the app and open it again). , Write these lines in onActivityResult method
code :
try {
     // get uri from Intent
     Uri uri = data.getData();
     // get bitmap from uri
     Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
     // store bitmap to file
     File filename = new File(Environment.getExternalStorageDirectory(), "imageName.jpg");
     FileOutputStream out = new FileOutputStream(filename);
     bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
     out.flush();
     out.close();
     // get base64 string from file
     String base64 = getStringImage(filename);
     // use base64 for your next step.
} catch (IOException e) {
     e.printStackTrace();
}

private String getStringImage(File file){
    try {
        FileInputStream fin = new FileInputStream(file);
        byte[] imageBytes = new byte[(int)file.length()];
        fin.read(imageBytes, 0, imageBytes.length);
        fin.close();
        return Base64.encodeToString(imageBytes, Base64.DEFAULT);
    } catch (Exception ex) {
        Log.e(tag, Log.getStackTraceString(ex));
        toast("Image Size is Too High to upload.");
    }
    return null;
}
byte[] bytes = Base64.decode(base64.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView) this.findViewById(R.id.ImageView);
image.setImageBitmap(
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
);
Related Posts Related Posts :
  • Unsupported field: Year when formatting an instant to Date ISO
  • java serialize transient elements
  • why the program hang up when using ArrayBlockingQueue
  • Data objects conversion - instance method vs static method
  • Which checksum algorithm is being used by adobe acrobat pdf for file attachment
  • how to get list of all available images for a region in amazon web services using aws-java-sdk?
  • BufferedReader can not read the int in text
  • How to configure hadoop's mapper so that it takes <Text,IntWritable>
  • Change name of libGDX DesktopLauncher in mac OSX menu bar
  • parse the json file with mutiple objects using Jackson
  • It the planning entity must have one to one relationship with planning value?
  • My code is showing error
  • How can I modify the colors of pixels in a Texture?
  • compiling and executing java from bash script
  • How to test Spring mvc controller tests for response entity?
  • How to Switch between Native Mobile App to Web Application to verify the elements on it
  • Command 'web mvc all --package ~.web' not found
  • Reverse an array using swapping in Java
  • Trying to create a chessboard using an array and graphics
  • Can DatagramSocket Receive multicast Packets
  • What is abstract data type ? Is it a class in Java?
  • Non-gui checkout register menu: how to format it?
  • Glassfish The server exited prematurely with exit code 134
  • android: SharedPreferences not saving data
  • How to implement different log output by classloader in just one Java application?
  • Migrating to Google Cloud Endpoints Framework for Java
  • Does the Swing event dispatch thread run at higher priority than the main thread?
  • Android Studio Failing to Store Arguments as Part of Fragment Bundle
  • Reading a JSON Array in JAVA
  • Faster way (performance) to check if a letter is uppercase?
  • How to generate a .wav file with a sinusoidal wave and user-defined duration and frequency?
  • Compare int values from objects in an array list, and then display the top 3 objects
  • Producing the Nth value of Fibonacci Sequence in Java
  • Kafka ACL authorization issue using Java code
  • easiest way to access to device credentials from a Driver implementation?
  • YoutubeThumbnailLoader taking too long to show a thumbnail?
  • Java inheritance why does this toString prints BB and not AB, AB?
  • how to set up a while loop for
  • Processing 3.x not recognizing random() function
  • Understanding 2D Arrays in Java
  • Counting a String's Lowercase Letters
  • Target folder is there but still getting no file found error, what can be the reason?
  • Cannot call constructor component from ActionPerformed
  • How does java global variable work?
  • How to use a Java variable with LIKE and '%' in sql?
  • Converting code using array to a code using Stacks/Queue
  • Product of two numbers using recursion java
  • Utility class : EJB Session or Simple Object?
  • XML won't load class TestNG Java
  • Getting Called From Wrong Thread Exception
  • Saving Dates to a serialized file
  • Class for added dependency not found for Java Web WAR deployed to heroku tomcat
  • The timer not let the user to edit
  • MongoDb multiple sort
  • Why does Google Play say my app is incompatible with devices it should be working on?
  • Java How to sort an array of signed integers in descending order ignoring the signs?
  • Printing rows of increasing amounts of even numbers
  • Stream is closing in twitter4j (Hadoop- flume)
  • javafx tableview column resizing issue
  • In Java FutureTask if the task Times out, does the Task get Cancelled?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com