Image Encoding

Hi
I have an xml file and I read my data from it, but my question is:
how can I encode the image and then write it into this file? since I want to let my application read the encoded image from the xml file and then store it to Record Store.
Please any help will be so appreciated :(
thanks in advanced

your code didn't work with me, but many thanks for your helping.
I searched for another code and i found this code and it's work fine :)
/* Copyright (c) 2002,2003, Stefan Haustein, Oberhausen, Rhld., Germany*/
package Files;
import java.io.*;
public class Base64 {
    static final char[] charTab =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();
    public static String encode(byte[] data) {
        return encode(data, 0, data.length, null).toString();
    /** Encodes the part of the given byte array denoted by start and
    len to the Base64 format.  The encoded data is appended to the
    given StringBuffer. If no StringBuffer is given, a new one is
    created automatically. The StringBuffer is the return value of
    this method. */
    public static StringBuffer encode(
        byte[] data,
        int start,
        int len,
        StringBuffer buf) {
        if (buf == null)
            buf = new StringBuffer(data.length * 3 / 2);
        int end = len - 3;
        int i = start;
        int n = 0;
        while (i <= end) {
            int d =
                ((((int) data) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 0x0ff) << 8)
| (((int) data[i + 2]) & 0x0ff);
buf.append(charTab[(d >> 18) & 63]);
buf.append(charTab[(d >> 12) & 63]);
buf.append(charTab[(d >> 6) & 63]);
buf.append(charTab[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append("\r\n");
if (i == start + len - 2) {
int d =
((((int) data[i]) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 255) << 8);
buf.append(charTab[(d >> 18) & 63]);
buf.append(charTab[(d >> 12) & 63]);
buf.append(charTab[(d >> 6) & 63]);
buf.append("=");
else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;
buf.append(charTab[(d >> 18) & 63]);
buf.append(charTab[(d >> 12) & 63]);
buf.append("==");
return buf;
static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '+' :
return 62;
case '/' :
return 63;
case '=' :
return 0;
default :
throw new RuntimeException(
"unexpected code: " + c);
/** Decodes the given Base64 encoded String to a new byte array.
The byte array holding the decoded data is returned. */
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
catch (IOException e) {
throw new RuntimeException();
return bos.toByteArray();
public static void decode(String s, OutputStream os)
throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;
if (i == len)
break;
int tri =
(decode(s.charAt(i)) << 18)
+ (decode(s.charAt(i + 1)) << 12)
+ (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));
os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);
i += 4;

Similar Messages

  • Image encoding in XML report definition

    For a number of reports I have the Report definition in XML-format. These files contain embedded images.
    How do I extract image-files from the xml's. It doesn't look like the strings for the images are not base16 or base64 encoded?

    Are you working with something like this?
    <?xml version="1.0" encoding="WINDOWS-1252" ?>
    <report name="MODULE1" DTDVersion="9.0.2.0.10">
      <xmlSettings xmlTag="MODULE1" xmlPrologType="text">
      <![CDATA[<?xml version="1.0" encoding="&Encoding"?>]]>
      </xmlSettings>
      <data>
        <systemParameter name="MODE" initialValue="Default"/>
        <systemParameter name="ORIENTATION" initialValue="Default"/>
      </data>
      <layout>
      <section name="main">
        <body>
          <image name="B_1">
            <geometryInfo x="0.00000" y="0.00000" width="8.31250" height="6.25000"
            />
            <visualSettings fillPattern="transparent" fillBackgroundColor="black"
             linePattern="transparent" lineBackgroundColor="black"/>
            <points>
              <point x="0.00000" y="0.00000"/>
              <point x="8.31250" y="6.25000"/>
              <point x="0.00000" y="0.00000"/>
              <point x="8.31250" y="6.25000"/>
            </points>
            <binaryData encoding="hexidecimal" dataId="image.B_1">
    FF8DFF0E 0001A464 94640010 10100006 00060000 FFBD0048 0001B0C0 E0C0A001
    E0D0E021 11013181 82A18161 61811332 52D182A3 33D3C393 33837304 84C5E404
    44755473 8305D615 75F52676 8676E3D4 17970746 87C55676 36101121 21815181
    F2A1A1F2 36248324 36363636 36363636 36363636 36363636 36363636 36363636
    36363636 36363636 36363636 36363636 36363636 36363636 3636FF4C 102A0000
    D29681A8 4EB94557 F3D8D588 912F1FCE A2478278 4E157FE8 D3B2F257 A1906D14
    A809D102 9F646EFF 007CA66A B08C98EF 2E5344BB 4978EEAD 55093F75 6A4E8D29
    345ECCA0 4F537A2C 9CB424CB 8DDE0D7D 53D4D002 D3E32E6D 1942F70F 5D29740C
    7CF15A56 1A469E72 F449A09D 918DE7CF 5F9F877A 17106FEF 474C484E 6F41C067
    0D1338AF 1D06311A 4E6608F0 F4C40540 859FBFE7 579924E1 495C31FF 9D
            </binaryData>
          </image>
        </body>
      </section>
      </layout>
      <webSource>
      <![CDATA[<%@ taglib uri="/WEB-INF/lib/reports_tld.jar" prefix="rw" %>
    <%@ page language="java" import="java.io.*" errorPage="/rwerror.jsp" session="false" %>
    <%@ page contentType="text/html;charset=ISO-8859-1" %>
    <!--
    <rw:report id="report">
    <rw:objects id="objects">
    </rw:objects>
    -->
    <html>
    <head>
    <meta name="GENERATOR" content="Oracle 9i Reports Developer"/>
    <title> Your Title </title>
    <rw:style id="yourStyle">
       <!-- Report Wizard inserts style link clause here -->
    </rw:style>
    </head>
    <body>
    <rw:dataArea id="yourDataArea">
       <!-- Report Wizard inserts the default jsp here -->
    </rw:dataArea>
    </body>
    </html>
    <!--
    </rw:report>
    -->
    ]]>
      </webSource>
      <reportPrivate versionFlags2="0" templateName="rwbeige"/>
      <reportWebSettings>
      <![CDATA[]]>
      </reportWebSettings>
    </report>Image data is encoded in hexadecimal format (base16) but the hex digits are reversed compared to the original byte sequence.
    For example, the first eight bytes in the source are :
    FFD8FFE0 00104A46but appears as FF8DFF0E 0001A464 in the XML file.
    You'll need a small program to read the file, extract the hex binary stream, process it and write back the data to a file.
    Example in PL/SQL (tested on db version 11.2.0.2) :
    DECLARE
    fid     utl_file.file_type;
    len     PLS_INTEGER := 1024;
    buf     RAW(512);
    module_name VARCHAR2(260) := 'MODULE1';
    dir_name    VARCHAR2(30) := 'TEST_DIR';
    BEGIN
      for r in (
        /* extract all image elements */
        select img_name
             , regexp_replace(img_data, '\s+') as img_data
        from xmltable('//body/image'
              passing xmltype(bfilename(dir_name, module_name||'.xml'), nls_charset_id('WE8MSWIN1252'))
              columns img_name varchar2(30) path '@name'
                    , img_data clob         path 'binaryData'
      loop
        /* output file */
        fid := utl_file.fopen(dir_name, module_name || '_' || r.img_name || '.jpg', 'wb', 32767);
        for i in 0..trunc((dbms_lob.getlength(r.img_data) - 1 )/len)
        loop
          /* read 1k of hex data and convert to binary */
          buf := hextoraw(
                   regexp_replace(
                     dbms_lob.substr(r.img_data, len, i*len + 1)
                   , '\2\1'
          utl_file.put_raw(fid, buf);
        end loop;
        utl_file.fclose(fid);
      end loop;
    END;
    /

  • Problem using PJA tools Gif/Image Encoder

    hi
    can someone tell me where i am going wrong ...I am getting the following error after i ran a servlet .
    Internal error: Unexpected error condition thrown (java.lang.NoClassDefFoundError: Acme/JPM/Encoders/ImageEncoder,Acme/JPM/Encoders/ImageEncoder), stack: java.lang.NoClassDefFoundError: Acme/JPM/Encoders/ImageEncoder
    at java.lang.ClassLoader.resolveClass0(Native Method)
    at java.lang.ClassLoader.resolveClass(ClassLoader.java:597)
    at com.iplanet.server.http.servlet.NSServletLoader.loadClass(NSServletLoader.java:114)
    at com.iplanet.server.http.servlet.NSServletEntity.load(NSServletEntity.java:337)
    at com.iplanet.server.http.servlet.NSServletEntity.update(NSServletEntity.java:173)
    at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:427)
    I added both the GifEncoder and ImageEncoder class files to the classpath . Still the same problem ...
    I need some help ..pls..
    prabhu

    Try copying the GifEncoder and ImageEncoder files or the jar file to the app server lib directory.

  • How to do? Asyncronous encoding of JPEG Image

    when ever we encode the bitmap data it will pause explorer for a time being ....................
    is there any way to do this asynchronous ......
    also i have tried alchemy lib....stil problem is not resolved ...
    thanks
    Rajesh Yadav

    I took a stab at it couple of months ago. Inside post you have other 2 links.
    However the time that it take for an asynchronous encoder to encode is sensibly bigger that the synchronous encoder.
    http://blog.claudiu-ursica.ro/2011/06/04/more-asynchronicity-asynchronous-image-encoding/
    HTH,
    C

  • My images look blurry when I export or publish my site from Muse. Why and how do I fix it?

    My images look blurry, jagged, pixelated and low quality when I publish or export my site from Muse. Is there any way to avoid or fix this problem?

    The primary cause of blurring images is the less than Photoshop-quality image downsampling algorithm currently used in Muse (that was compounded in early betas due to a bug in the JPEG compression library we were using at that time). Due to work we've done for Beta 7 to improve image encoding performance we now have the infrastructure in place to enable us to take a much better image resampler/resizer (after Beta 7), so this source of blurring will be addressed.
    The other source of blurring is unique to opaque images containing line art or otherwise containing hard edges and large areas of solid color. When an image is opaque Muse will encode it as JPEG (if it's altered in Muse is a way that requires re-encoding). For line art this will introduce JPEG compression artifacts that can be noticeable depending on your eye and the specific image involved.
    There are (at least) to ways to avoid these JPEG compression artifacts:
    Resize your image before placing and avoid applying any effects (rounded corners, drop shadow, etc.) or doing any cropping or resizing in Muse. If the image is unaltered your original JPEG, PNG or GIF will be passed through unaltered.*
    Put at least one pixel of transparency in your original image. (It could be a single 99% opaque pixel.) This will force Muse to encode as PNG. PNG compression is lossless and thus doesn't introduce any compression artifacts. However, an average PNG can be 5 times the size of a JPEG for the same image, so there is an impact to webpage download performance.
    *For PSD files Muse has to encode the original PSD data into some web-friendly image format. If an image is resized in Photoshop and placed Muse won't resize/resample the image data, but it will encode it as JPEG or PNG depending on whether it contains transparency.

  • How to retain the same resolution while croping a tiff image using jai api

    Hi all,
    I have designed a program to crop a tiff image.But after croping the tiff,the resultant file resolution is not the same as the original source file.
    In the program,the source file Nadeshiko_v1_02.tif has the resolution(X) of 1200 DPI and resolution(Y) has 1200 DPI pixels.
    But after croping the resolution of output file is 100 DPI.
    Please give me some idea on how to retain the same resolution.
    <code>
    package jai;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import java.awt.image.renderable.RenderableImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.imageio.*;
    import javax.imageio.stream.ImageOutputStream;
    import javax.media.jai.Interpolation;
    import javax.media.*;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import javax.media.jai.RenderedOp;
    import javax.media.jai.widget.ScrollingImagePanel;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.TIFFEncodeParam;
    import javax.media.jai.OperationDescriptorImpl;
    import java.io.*;
    import java.util.Iterator;
    import javax.media.jai.operator.*;
    // import javax.media.jai.widget.ScrollingImagePanel;
    public class crop {
              /** The main method. */
    public static void main(String[] args) {
    /* Validate input. */
    /* if (args.length != 1) {
    System.out.println("Usage: java JAISampleProgram " +
    "input_image_filename");
    // System.exit(-1);
    float a=(float) 70.3;
    float b=(float) 70.4;
    float c=(float) 3100.3;
    float d=(float) 5522.4;
    * Create an input stream from the specified file name
    * to be used with the file decoding operator.
    String TIFF="TIFF";
    FileSeekableStream stream = null;
    try {
         stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_02.tif");
    // stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_01.jpg");
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    // Load the source image from a Stream.
    RenderedImage im = JAI.create("stream", stream);
    RenderedImage image2= CropDescriptor.create(im, a, b, c, d, null);
    ScrollingImagePanel panel = new ScrollingImagePanel(image2, 100, 100);
    // Create a frame to contain the panel.
    Frame window = new Frame("JAI Image Cropping");
    window.add(panel);
    window.pack();
    // window.show();
    // Define the source and destination file names.
    // String inputFile = "D:\\tif images\\Nadeshiko_v1_05.tif";
    String outputFile = "D:\\tif images\\Nadeshiko_v1_04.tif";
    // Save the image on a file. We cannot just store it, we must set the image encoding parameters
    // to ensure that it will be stored as a tiled image.
    TIFFEncodeParam tep = new TIFFEncodeParam();
    tep.setWriteTiled(true);
    tep.setTileSize(80,80);
    JAI.create("filestore",image2,outputFile,"TIFF",null);
    try {
                   stream.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    </code>
    Thanks,
    Sanat Meher

    Try the following,
    TIFFEncodeParam tep = new TIFFEncodeParam();
    // Create {X,Y}Resolution fields.
    TIFFField fieldXRes = new TIFFField(0x11A, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_X, 1}});
    TIFFField fieldYRes = new TIFFField(0x11B, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_Y, 1}});
    tep.setExtraFields(new TIFFField[] {fieldXRes, fieldYRes});

  • Adobe Media Encoder - File Size HUGE. HELP

    I have a MPG that is 216mb. When I attempt to use Media Encoder 5 or 5.5 the estimated file size for a 640 x 480 f4v is 26456mb.
    I have used the computer at my school with the same file and the file size is 2mb. What am I doing wrong at home? I can't image encoder can make a 216mb file become 2.6 gb.
    Please help.
    Howard

    Please drop the source clip into MediaInfo and check what it says the duration is. (If you don't have MediaInfo, you can download it for free from the Internet.) If possible, please post a link to the clip so that we can download it and check it out for ourselves.
    Two details catch my eye in the Source Summary. Both screenshots show that the field order is Unknown and that the clip has no audio. I doubt either of those details accounts for the incorrect duration, but the unknown field order, at least, makes me wonder whether AME is having trouble interpretting the footage correctly. I suggest going to the Interpret Footage dialog (right-click on the clip in AME's queue and select Interpret Footage), and setting the Field Order to the correct value [Upper Field First, Lower Field First, or No Fields (Progressive Scan)]. While you're there, check whether the frame rate is accurate--according to the screenshot, it's 30.000 fps. Is that accurate?

  • Showing various images on browser using JSP and Servlet

    Hello Guys!
    I am starting to develop in Java and already I am facing a big problem.
    If somebody will have some tip or suggestion, will be very well comings!
    The application must present in browser images originnally of format TIF. As it is not a native format of the I.E. , I converted the image for JPG (without saving it on disk) and send it to the browser a encoded image (encode) using JAI library in one servlet had access by a JSP. Then, the structure of my application is thus:
    1) an archive JSP draws the initial screen in browser and presents one input text.
    2) later that the user places the parameter, I make an access to the database and read a quantity of images to be presented.
    3) From there in the proper JSP, I use de tag img src to send image to the browser in agreement archive the amount of images.
    It follows the code of the JSP:
    <% 
                    int intI=0;
                    int intCont=0;
                    if(blnImagem == true){
                        out.println("<br>");
                        out.println("<table border=0 STYLE=border-collapse:collapse>");
                        out.println("<tr>");
                        for(intI=0;intI < Processo.intQtdImagens;intI++){
                           Imagem.strImgTif = Imagem.IndicarImagem(Processo.strNmPath,Processo.strSubPath,Processo.intNuImagem,intI);                                                                    
                           out.println("<th>");
                           out.println("<table border=1 STYLE=border-collapse:collapse rules='cols'>");
                           out.println("<tr>");
                           out.println("<th>");
                           %>
                             <img src="ShowImg" WIDTH=100>
                           <%
                           out.println("</th>");
                           out.println("</tr>");
                           out.println("</table>");
    %>and code on the ShowImg servlet:
            response.setContentType("image/jpeg");       
            ServletOutputStream sos = response.getOutputStream();
            RenderedOp src = JAI.create("fileload", Imagem.strImgTif);           
            ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG",sos,null);       
            encoder.encode(src); 
            sos.close();The problem is if I have 10 images to present, it WILL BE it is executed 10 times and it passes 10 names of different archives, but in the page only the last image is presented 10 times. It is as if it processed the TAG to the end of everything in way that the value of the static variable Imagem.strImgTif was chore only with the last value and the same loaded image 10 times. How I make to solve this? Somebody has some idea?
    THANK YOU !
    Emidio

    If I understand correctly what your problem is:
    Do this in the jsp:
    out.println("<img src=\"ShowImg?image=" + intI + "\" WIDTH=100>");
    In the image servlet, get the "image" parameter and parse it as an int. Move the Imagem.IndicarImagem() call to the image servlet.

  • Saving canvas as an image: embedded in an applet

    hi everyone,
    I'm trying to save shapes I've drawn in a canvas as a jpg. This works, thanks to a solution I found somewhere in one of these forums. However, I need to embed the application in an applet, and in that case it doesn't work anyone. Here is some code that works when I don't use applets:
    public class MenuItemHandler implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   try{
                        FileDialog fd = new FileDialog(new Frame(), "Save as JPG", FileDialog.SAVE);
              fd.setFile("canvas.jpg");
              fd.setVisible(true);
              String name = fd.getDirectory() + fd.getFile();
              File file = new File(name);
                        ImageUtils utils = new ImageUtils();
                        BufferedImage image = utils.createComponentImage(tc);
                        utils.encodeImage(image,file);
                   catch(Exception ex) {
                        ex.printStackTrace(); }
         class ImageUtils {
              private JPEGImageEncoder encoder = null;
              private FileOutputStream fileStream = null;
              public BufferedImage createComponentImage(Component component){
                   BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
                   Graphics graphics = image.getGraphics();
                   if(graphics != null) { component.paintAll(graphics); }
                   return image;
              public void encodeImage(BufferedImage image, File file) throws IOException{
                   fileStream = new FileOutputStream(file);
                   JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
                   encoder = JPEGCodec.createJPEGEncoder(fileStream);
                   encoder.encode(image,encodeParam);
                   fileStream.close();
    When the code is embedded in an applet, I see my appliaction and I get my save dialog box, but there won't be written any file anymore. I suppose it has something to do with the fact that I don't use getDocumentBase() or getCodeBase(), but I'm not sure about that, and if this is the reason, I don't know exactly how to implement it in the code.
    I hope that someone can help me!!
    Thanks in advance!

    hi everyone,
    I'm trying to save shapes I've drawn in a canvas as a jpg. This works, thanks to a solution I found somewhere in one of these forums. However, I need to embed the application in an applet, and in that case it doesn't work anyone. Here is some code that works when I don't use applets:
    public class MenuItemHandler implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                   try{
                        FileDialog fd = new FileDialog(new Frame(), "Save as JPG", FileDialog.SAVE);
              fd.setFile("canvas.jpg");
              fd.setVisible(true);
              String name = fd.getDirectory() + fd.getFile();
              File file = new File(name);
                        ImageUtils utils = new ImageUtils();
                        BufferedImage image = utils.createComponentImage(tc);
                        utils.encodeImage(image,file);
                   catch(Exception ex) {
                        ex.printStackTrace(); }
         class ImageUtils {
              private JPEGImageEncoder encoder = null;
              private FileOutputStream fileStream = null;
              public BufferedImage createComponentImage(Component component){
                   BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
                   Graphics graphics = image.getGraphics();
                   if(graphics != null) { component.paintAll(graphics); }
                   return image;
              public void encodeImage(BufferedImage image, File file) throws IOException{
                   fileStream = new FileOutputStream(file);
                   JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
                   encoder = JPEGCodec.createJPEGEncoder(fileStream);
                   encoder.encode(image,encodeParam);
                   fileStream.close();
    When the code is embedded in an applet, I see my appliaction and I get my save dialog box, but there won't be written any file anymore. I suppose it has something to do with the fact that I don't use getDocumentBase() or getCodeBase(), but I'm not sure about that, and if this is the reason, I don't know exactly how to implement it in the code.
    I hope that someone can help me!!
    Thanks in advance!

  • Problem in Saving Image Code

    Hi, I'm been dealing with this code that should be saving an image as a JPEG format.
    public static void saveAsJPEG(RenderedImage image, String file)
    throws java.io.IOException {
    String filename = file;
    if(!filename.endsWith(".jpg"))
    filename = new String(file+".jpg");
    OutputStream out = new FileOutputStream(filename);
    JPEGEncodeParam param = new JPEGEncodeParam();
    ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, param);
    encoder.encode(image); out.close(); }
    However, when I compile the code, there's an error come out : com.sun.image.codec.jpeg.JPEGEncodeParam is abstract; cannot be instantiated
    I really can't figure out the meaning of this exception. So, would somebody kindly tell me what is wrong with the code?
    And another question is : What package is the ImageCodec located? Thanks a lot :)

    try this out and let me know;
    public static void saveAsJPEG(BufferedImage image, String file)
    throws java.io.IOException {
    String filename = file;
    if(!filename.endsWith(".jpg")) filename = new String(file+".jpg");
    OutputStream out = new FileOutputStream(filename);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // Create JPEG encoder
    JPEGEncodeParam jpegParams = encoder.getDefaultJPEGEncodeParam(image);
    jpegParams.setQuality(1.0f, false); // Set quality to 100% for JPEG
    encoder.setJPEGEncodeParam(jpegParams);
    encoder.encode(image); // Encode image to JPEG and send to browser
    //JPEGEncodeParam jpegPparams = new JPEGEncodeParam();
    //ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, jpegParams);
    //encoder.encode(image);
    out.close(); }

  • Images in email signatures bug on Reply (Mail)

    Hi,
    I'm using Mail as email software.
    I have some problems with email signatures, when I reply to these emails.
    The signatures contained in these mails contain HTML images encoded via base_64.
    If I forward the message, there's no problem with images included.
    But if I reply to the message, images appear as encoded characters.
    What's the problem? Do I have to change any setting ? Or do I have to adapt the image's encoding ?
    Thanks for your help!
    Arnaud

    Hi Karl,
    so you tried the IMG tag and it does not work for you?
    For example
    would in CDT view turn out like
    Though one potential problem with this is that depending on the receiver's e-mail client it may block auto-download of external images.
    BR,
    -Lasse

  • Best way to place lots of images into one

    Hello,
    I have made a Javascript script that loops between 20.000+ images and puts them into a main image. Code is:
    var sampleDocToOpen = File('~/a/'+(l+startF)+'/'+(i+start)+'.png')
    open (sampleDocToOpen)
    app.activeDocument.selection.selectAll()
    app.activeDocument.selection.copy()
    app.activeDocument.close()
    app.documents[0]
    app.activeDocument.paste()
    it works, but it is extremely slow (I also have the main image flattened every 30-40 images to make it quicker).
    So i tried to place the images directly into the main image via:
    function placeFile(file) {
         var desc = new ActionDescriptor();
         desc.putPath( charIDToTypeID('null'), file );
         desc.putEnumerated( charIDToTypeID('FTcs'), charIDToTypeID('QCSt'), charIDToTypeID('Qcsa') );
             var offsetDesc = new ActionDescriptor();
             offsetDesc.putUnitDouble( charIDToTypeID('Hrzn'), charIDToTypeID('#Pxl'), 0.000000 );
             offsetDesc.putUnitDouble( charIDToTypeID('Vrtc'), charIDToTypeID('#Pxl'), 0.000000 );
         desc.putObject( charIDToTypeID('Ofst'), charIDToTypeID('Ofst'), offsetDesc );
         executeAction( charIDToTypeID('Plc '), desc, DialogModes.NO );
    But after opening few images it says that "scratch disks are full", and I verify that it is true since almost 500GB of the HD are used by the application... Images are 512x512 each, thus the resulting image main image is 83456x63488.
    Is there a faster way I could try to use??
    Thanks a lot!

    And also realize what is going on. First your using a script. Though a script is a program with logic its source code which is not compiled into machine code its has to be intrepided into machine executable code as the script processor  iterate through your buffered source code. This itself takes time. Then you have to understand what is happening in your loop and what Photoshop has to do once the Script code can be executed.  Using Copy and Paste or Place requires Photoshop to open and read in 20,000 encoded jpeg images files and one way or the other decode the encoded image for rendering to copy it to the Clipboard  or render the embedded smart object copy into the Smart Object Layer. Then there is the other code that you have to add canvas and distribute the images layers across the canvas. Intrepiding the script source code some 20,0000 times is something like doing 20,000 compiles where the source code is only read in once but is turned into machine executable code 20,0000 times.  To process 20,000 encoded images files using a full feature image Editor program and a scripting process is going to take a long tome and require a lot of machine resources.  If you want a fast solution you will need custom compiled program designed for your process. Still reading and decoding 20,000 small jpeg image files is going to take some time and require quite a bit of machine resources. It might be better to use an image file format that doesn't use compression and complex image encoding to cut down on the amount of processing reqruired .  

  • [Tip] How to protect Image file

    Hello,
    If you have ever wanted to protect your image file,
    especially within your Flash content,
    this article will be helpful.
    First of all, there are some points you need to protect when
    you deliver image data with Flash.
    1. Internet Browser Cache.
    Even though you use 'HTTPS' protocol when you deliver your
    file,
    if it is pass the 'Network (or Protocol) Layer' of your
    machine, it is already in 'plain' data
    (not encrypted), and can be read by Internet Browser.
    Those 'plain' data will be stored in Internet Browser's
    Cache directory.
    There are many Internet Browser Cache reader programs, and
    they can intercept those
    data before the Internet Browser program deletes the cache
    files.
    So, just using 'HTTPS' is not an answer. You need to encode
    your image data
    with your own (or with well known cypher algorithms)
    encoding/decoding methods.
    In this article, I want to explain more detail about this. I
    scramble the image
    so that make it hard to figure out what the original image
    was, not only with human eyes
    but also with 'strong enough' 'Key' length.
    2. Screen Capture.
    Even if you encoded your image data, it will be finally
    shown on your screen,
    without any noises, or any other ugly filters.
    So, you can 'Capture' your monitor screen itself.
    There can be many ways to avoid this. First, you can erase
    the system's 'Clip board'.
    You just can erase it regularly, or you can detect whether
    the Internet Browser -which is
    showing your image data- is active or not and erase clip
    board when it is active (in foreground),
    and hide your Flash area when the browser is inactive (in
    background).
    If a hacker just take a picture of monitor screen with high
    quality Camera,
    you still can avoid that, by showing some black rectangle,
    or any layers on the screen
    regularly only in very short period (like mili-second). But
    I think this way sometimes you feel
    tired or be annoyed when you watch that kind of blinking
    screen.
    == About my code ==
    What I want to present here today is 'modifying(encoding) the
    image' data itself.
    There are many ways you can try for modifying your image data
    and revert it back to original data.
    You can use legacy block cipher algorithms like DES, AES, for
    encoding and decoding the
    image data, because the image data (RGB values) what Flash
    uses is actually a combination of 'bit's.
    But if you decode the 'encoded image' data, you probably use
    'get pixel'/'set pixel' function for
    reconstructing the proper 'RGB' value of each pixel. But I am
    sorry that this function is extremely slow
    so that you need to wait for a couple of minutes to see an
    image.
    So, what I want to show you today is 'Scrambling the image'
    like 'picture puzzle',
    with using 'copyPixels' function which is 'extremely fast'.
    (Actually, there can be many other solutions for this, so
    please don't hesitate to proceed your own research)
    Let's say you have 8*8 pixel size of image blocks, and you
    completely disorder those blocks for
    entire image area. That size of block is too small to figure
    out where it should be, with our
    humble human being's naked eyes. So, you need to know the
    'answer', which is saying what image block
    was originally on which 'cell'. This 'answer' is the 'key'
    for my simple 'image scramble' logic.
    The 'key' I said here, you should understand that, is the
    'key' value of normal 'block cipher' algorithms.
    So, if you know the key, you can rearrange all those 'blocks'
    back, but if you don't know the key,
    simply you can't do that, or you need to wates tremendous
    time for that.
    Here, I use 16*16 size block for your eye's convenience, and
    with 8*8 size of 'matrix' which is
    comprised of each 16*16 size blocks. I mean, one 8*8 matrix
    has 64 blocks, so each block of
    one 'matrix' can be at '1st cell of matrix or 64th cell of
    matrix. So, the 'odds' is 'Factorial of 64',
    which is 64! == 1.268869322e+89 .
    Let's say you know my algorithm (complete source code), and
    you try every different 'matrix' values.
    If it takes 0.001 seconds to test one 'matrix' value you have
    chosen, it will take
    "(64!) / (1000*60*60*24*365) =
    4.0235582250724303685766549129617e+78" Years!!!! to find exact
    matrix value.
    == FLA sample ==
    In my sample *.fla file, I embedded all those 'key' values.
    So, you can not use my sample directly for your
    own project. But I think this sample will give you an useful
    idea for your own implementation.
    <* Exchanging the key values *>
    For example, you need to get the 'key' values from the
    server, only when it is needed.
    You can use 'loadVariables()' function for this purpose.
    But, all data delivered by 'loadVariables()' or
    'getUrl()', or any other functions of Flash, are
    'Cached'.... So, you need to exchange that 'key' values
    more safer way.
    One of that 'safer key exchange' is to use 'token'. For
    example, when the client requests the key value
    to the server, the client should generate an random value (I
    will call it 'token') and send it to the server.
    Now the server modifies the 'key' value 'with the token',
    and sends back to client. Finally, the client
    decode the 'key' value with the token value it generated.
    As you can see, my logic is just 'rearranging each blocks'
    with respond to the given matrix values (key).
    It is really really simple. There in the ActionScript code,
    you can see 3 matrix, and some other variables.
    var chessunit = 16 // Size of block
    var arrayw = 8 // Width of Matrix
    var arrayh = 8 // Height of Matrix
    var arraysize = arrayh * arrayw
    var chessarray = Array (arraysize) // Matrix for decoding
    chessarray = Array
    (64,37,5,35,45,25,52,38,12,61,34,23,3,26,39,58,32,28,17,2,60,16,59,19,57,48,43,18,47,21,4 0,15,31,6,44,46,30,51,27,56,20,24,13,7,42,1,49,54,36,53,9,50,4,8,10,14,33,11,22,63,55,29,4 1,62)
    // In case of the width of an image is not exactly the
    multiple of the width of matrix,
    // we need to encode the right most area of the image.
    // So, I simply use another matrix for only that area.
    // Maybe You can generate more bigger image, of which the
    width of it is exactly the multiple of
    // the width of matrix. And you let the decoder to show only
    the original size of the image.
    // Please try yourself. :)
    var dwArray = Array
    (32,19,3,18,23,13,26,6,31,17,12,2,20,29,16,14,9,1,30,8,10,24,22,11,15,28,7,4,21,25,27,5)
    // In case of the Height of an image is not exactly the
    multiple of the Height of matrix,
    // we need to encode the bottom most area of the image.
    // So, I simply use another matrix for only that area.
    // Maybe You can generate more bigger image, of which the
    Height of it is exactly the multiple of
    // the Height of matrix. And you let the decoder to show
    only the original size of the image.
    // Please try yourself. :)
    var dhArray = Array
    (40,23,4,22,29,16,33,24,8,38,21,15,2,17,37,20,18,11,1,10,12,36,30,27,13,25,28,14,19,32,35 ,7,5,26,3,31,34,6,9,39)
    You can change the block size, matrix size, any values you
    want.
    By the way, if the block size becomes smaller, you'll get
    more stronger security level. But you have to
    compensate it with the slow down of the performance.
    ** Ooops, I can not attach my sample *.fla file, but only
    ActionScript code here...
    But I believe you can try without testing my *.fla sample.
    If you really want to test it, please mail me.
    ([email protected])
    ** You need to 'export' image object, with the name of
    "img0".
    == Image encoder ==
    Encoding (Scramble) the original image is also simple. You
    just need to copy each blocks in reverse of
    the 'ActionScript code'. That's all. You just use same
    'matrix', but copy source and target reverse of
    ActionScript code. I think you can write it with any
    languages you like, C/C++, C#, Java, and
    anything.... right?
    == Block cipher ==
    Now, you know that my implementation is kind of 'intuitive'
    representation of 'block cipher'.
    More precisely, it is called 'ECB', which encodes each
    encoding block (matrix) with the key values
    from the beginning to the end. You can twist the matrix every
    time you pass one matrix area of an image.
    It is called 'chaining'. There are some 'chaining' block
    cipher methods like 'CBC'...
    (If you want to know more, please look up "
    http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
    Thank you for your time to read my humble article,
    and wish you Good luck. :)

    Hello Crandom,
    If you want to encrypt a critical strings, like special
    server script url or parameters, then it is simple.
    The most simple and faster method is to "XOR ing the string"
    with a key string. You use the same key string when you encode and
    decode (by Just using XOR). This is similar to 'Stream cipher'
    algorithms.
    And there is "open source cipher algorithm" (called
    AS-CryptoLib) written in ActionScript, including most of algorithms
    like Hash, Block cipher, RSA... if you want more stronger
    encryption strength..
    But I bet you also want to encode your script logic itself.
    In that case, you should write your own 'Interpreter'. For example,
    you encode all your ActionScript source code string, and decode it,
    and you interpret each script tokens like 'if' 'for' 'while',
    etc...
    Actually, your question also inspired me to think about
    loading script string and run it on the fly.
    Maybe.... we can start from this article...
    http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_16691"
    I suggest you just use commercial SWF file encrypting tools
    like Ameyata's "SWF encrypt". It changes the SWF file structure so
    that usual 'SWF file decompilers' can not read codes properly.
    And.... If you can use Flex2 (for your current project), and
    it is ok with you (If you don't need to change a lot in your
    current project) to use JavaScript to control your objects or
    behavior of SWF file, then I think there is another possible way.
    After you decode the Javascript string, you load a web page,
    or change the content of HTML file already opened, so that your new
    script will be working, as what you wanted to be. But I didn't test
    it :)
    Best regards.

  • 16 bit Intensity to JPEG image

    Hi,
    I have an input file with 16 bit intensity values. I want to creat JPEG image from this file. Here is my source code:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.ImageIO;
    public class CreateJpeg extends Frame{
    private BufferedImage img = null;
         public static int[][] getData(File f) throws IOException {
              ArrayList line = new ArrayList();
              BufferedReader br = new BufferedReader(new FileReader(f));
              String s = null;
              while ((s = br.readLine()) != null)
                   line.add(s);
              int[][] map = new int[line.size()][];
              for (int i = 0; i < map.length; i++) {
                   s = (String) line.get(i);
                   StringTokenizer st = new StringTokenizer(s, "\t");
                   int[] arr = new int[st.countTokens()];
                   for (int j = 0; j < arr.length; j++)
                        arr[j] = Integer.parseInt(st.nextToken());
                   map[i] = arr;
              return map;
         public CreateJpeg (ColorModel colorModel, WritableRaster raster)throws IOException{
              img = new BufferedImage(colorModel, raster, false, null);//new java.util.Hashtable());
              show();
              ImageIO.write( img, "jpeg" , new File("new.jpeg"));
         public void paint (Graphics g) {
    g.drawImage (img, 0, 0, this);
         public static void main(String[] args) throws Throwable {
              int[][] map = getData(new File(args[0]));
              int[] OneDimImage = new int[map.length*map[0].length];
              for (int i = 0; i < map.length; i++) {
                   for (int j = 0; j < map.length; j++){
                        OneDimImage[i * map[0].length + j] = map[i][j];
              DataBuffer dbuf = new DataBufferInt(OneDimImage, map[0].length*map.length);
    WritableRaster raster = Raster.createPackedRaster(dbuf,map[0].length, map.length,
              map[0].length, new int[] { 0xff00, 0xf0, 0xf}, null);
              ColorModel colorModel = new DirectColorModel(16, 0xff00, 0xf0, 0xf);
              new CreateJpeg(colorModel, raster);
    After compiling and running this file, I got the following messages:
    Exception in thread "main" java.lang.IllegalArgumentException: Raster IntegerInt
    erleavedRaster: width = 800 height = 938 #Bands = 3 xOff = 0 yOff = 0 dataOffset
    [0] 0 is incompatible with ColorModel DirectColorModel: rmask=ff00 gmask=f0 bmas
    k=f amask=0
    at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    at CreateJpeg.<init>(CreateJpeg.java:28)
    at CreateJpeg.main(CreateJpeg.java:48).
    I will be pleased if anybody help me to solve this.
    Thanks

    No, short of getting a jpeg to use a lossless compression, this sequence:
    buffered image =encode=> jpeg file =decode=> buffered image
    is going to scramble data on the pixel level. If you use a high quality param value,
    like 1.0f, it will look good, but individual pixels won't be "close" to
    their original values, because that is not what the algorithm delivers.
    Demo:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    public class PngEnDecoder{
        public static void main(String[] args) throws Throwable {
            int w = 256, h = 1;
            int[] OneDimImage = new int[w*h];
            for (int i=0;i<w*h;i++)
                OneDimImage=i;
    DataBuffer dbuf = new DataBufferInt(OneDimImage, OneDimImage.length);
    int[] masks = { 0xff0000, 0xff00, 0xff};
    WritableRaster raster = Raster.createPackedRaster(dbuf, w, h, w, masks, null);
    ColorModel colorModel = new DirectColorModel(24, masks[0], masks[1], masks[2]);
    BufferedImage bi1 = new BufferedImage(colorModel, raster, false, null);
    File file = new File("test.jpeg");
    write(bi1, file, 1.0f);
    BufferedImage bi2 = convert(ImageIO.read(file), BufferedImage.TYPE_INT_RGB);
    WritableRaster raster1 = bi2.getRaster();
    DataBuffer db = raster1.getDataBuffer();
    DataBufferInt dbi = (DataBufferInt) db;
    int[] data = dbi.getData();
    for (int j=0;j<data.length;j++)
    System.out.println(data[j]);
    static void write(BufferedImage bi, File file, float quality) throws IOException {
    ImageOutputStream out = ImageIO.createImageOutputStream(file);
    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
    writer.setOutput(out);
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);
    writer.write(null, new IIOImage(bi, null, null),param);
    public static BufferedImage convert(BufferedImage source, int targetType) {
    int sourceType = source.getType();
    if (sourceType == targetType)
    return source;
    System.out.println("converting image type...");
    BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), targetType);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(source, null);
    g.dispose();
    return result;

  • Jpeg encoding with imageio - pink distortion problem

    Hello, I am using the imageio classes to scale down jpg images (for thumbnails) and write them to a file. On most images, everything works perfectly. On some images, however, the resulting thumbnail image has a strange pink coloration to the whole picture. Does anyone have any ideas as to why this would happen? The code I am using is below. I thank anyone that takes the time to read this and hope someone can help.
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.IndexColorModel;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
    import javax.imageio.stream.ImageOutputStream;
    public class ImageResizer
         private static final int THUMBNAIL_MAX = 120;
         private static final int SMALL_MAX = 250;
         private static final int LARGE_MAX = 575;
         private static final int LARGE_THRESHOLD = 425;
         BufferedImage inImage;
         int width;
         int height;
         private static JPEGImageWriteParam params;
         static {
              JPEGImageWriteParam params = new JPEGImageWriteParam(null);
              params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
              params.setCompressionQuality(0.8f);
              params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
              params.setDestinationType(
                   new ImageTypeSpecifier(IndexColorModel.getRGBdefault(),
                   IndexColorModel.getRGBdefault().createCompatibleSampleModel(16,16)));
         public ImageResizer(byte[] image, long id) throws IOException
              inImage = ImageIO.read(new ByteArrayInputStream(image));
              width = inImage.getWidth(null);
              height = inImage.getHeight(null);
         public void makeSmallImage (File outputFile) throws IOException {
              resizeImage(120, outputFile);
         private void resizeImage (int maxDim, File file) throws IOException {
              double scale = maxDim / (double) height;
              if (width > height) scale = maxDim / (double) width;
              int scaledWidth = (int)(scale * width);
              int scaledHeight = (int)(scale * height);
              BufferedImage outImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
              AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
              AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
              // Paint image.
              Graphics2D g2d = outImage.createGraphics();
              g2d.drawImage(inImage, op, 0, 0);
              g2d.dispose();
              // write the image out
              ImageOutputStream ios = null;
              try {
                   ios = ImageIO.createImageOutputStream(file);
                   ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next();
                   writer.setOutput(ios);
                   writer.write(null, new IIOImage(outImage, null, null), params);
                   writer.dispose();
              catch (IOException e) {
                   System.out.println("cought IOException while writing " +
                   file.getPath());
              finally {
                   if (null != ios) ios.close();
    }

    I am having the same problem with jpegs.
    The strange thing is that this only happends with the same exact code on OS X, while it never happens on any windows machine.
    I have tried using the the ImageIO classes, and a class I got off of this board a while back; however when using this class on an OS X machine, encoding takes a really long time and gives the pink distortion.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.*;
    import com.sun.image.codec.jpeg.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.geom.*;
    public class ImageUtils {
         private static JPEGImageEncoder encoder = null;
         private static FileOutputStream fileStream = null;
         public static BufferedImage createComponentImage(Component component)
              BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
              Graphics graphics = image.getGraphics();
              if(graphics != null) { component.paintAll(graphics); }
              return image;
         public static void encodeImage(BufferedImage image, File file) throws IOException
              fileStream = new FileOutputStream(file);
              JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
              encoder = JPEGCodec.createJPEGEncoder(fileStream);
              encoder.encode(image,encodeParam);
    }use it like this:
    File file = new File("ImageTest.jpg");
    image = ImageUtils.createComponentImage(imageCanvas);
    ImageUtils.encodeImage(image,file);

Maybe you are looking for

  • Macbook Pro won't startup after 10.9.1 update

    Early 2013 Macbook Pro 13" retina running Mavericks. Installed the 10.9.1 update and left it to do that and when I returned it had restarted in Bootcamp in Windows 8.1 Requested in Windows that it startup in OSX. On starting up OSX a message came up

  • Mini Firewire 800 Cables???

    I have been searching around the net in hopes of finding a really really small firewire 800 cable which I could use to connect two mobile hard drives together...I have the two drives stuck together with industrial strength velcro, and the ports of th

  • How to update schema-base xmltype by dba?error ORA-19007

    Hi , Connect to db using user 'u1', register schema to LOCAL and update schema-base xmltype success. Then I login in db as dba, update xmltype occus ORA-19007. If I register the schema to GLOBAL, using dba to update xmltype has no problem. But how to

  • Import/Open SVG Files in Fireworks CS5!

    Hey, I really need to import/open SVG files in Fireworks CS5. I have been searching the Web for days now, but I can't find anything. The reason for this is that I get thousands of files sent to me in SVG format that I needto incorporate into my desig

  • How to speed up applications and Mac OS X start?

    hello there, I find my applications start too slow on my Macbook pro Core Duo despite a T7400 Intel processor, 2,16 Ghz .Is Mac OS X for Intel Core Duo really optimized and his applications too? How can I speed up the performance of applications? I'm