Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Help with Reading PNG File, Base 64, encoding issue

    I need to read a PNG files contents using a file reader, convert the contents to a base 64 string, and then print them out. So far what I've tried is:

    public static String readFileAsString(String filePath) throws java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {
    f = new BufferedInputStream(new FileInputStream(filePath));
    f.read(buffer);
    } finally {
    if (f != null) try { f.close(); } catch (IOException ignored) { }
    }

    return new String(buffer);
    }

    //with the output from this function, I will call:

    public static String base64Encode(String s)
    {
    //From the apache commons library
    String encoded = Base64.encodeBase64String(s.getBytes());
    return removeLineBreaks(encoded);
    }

    //For compliance with the base64 standard that I'm using
    public static String removeLineBreaks(String s)
    {
    return Pattern.compile("[\\r\\n]").matcher(s).replaceAll("");
    }

    It's working fairly well, but random question marks are inserted throughout the output. The odd thing is, they are not inserted in place of other characters, but in addition. Any help would be appreciated.

  • #2
    New to the CF scene
    Join Date
    Feb 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Update

    I've found out that the problem actually happens during the file read.

    So, I'll modify my question to only being about how to read a PNG file.

    public static String readFileAsString(String filePath) throws java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {
    f = new BufferedInputStream(new FileInputStream(filePath));
    f.read(buffer);
    } finally {
    if (f != null) try { f.close(); } catch (IOException ignored) { }
    }

    return new String(buffer);
    }

    When I call this method on a PNG file, it adds in extra question marks throughout the file. Is this because of an encoding issue?

    Thanks,

    P


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •