001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.example.imagine.step1.codec; 021 022import org.apache.mina.filter.codec.ProtocolEncoderOutput; 023import org.apache.mina.filter.codec.ProtocolEncoderAdapter; 024import org.apache.mina.core.buffer.IoBuffer; 025import org.apache.mina.core.session.IoSession; 026import org.apache.mina.example.imagine.step1.ImageResponse; 027 028import javax.imageio.ImageIO; 029import java.awt.image.BufferedImage; 030import java.io.ByteArrayOutputStream; 031import java.io.IOException; 032 033/** 034 * an encoder for {@link ImageResponse} objects 035 * 036 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 037 */ 038public class ImageResponseEncoder extends ProtocolEncoderAdapter { 039 040 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { 041 ImageResponse imageResponse = (ImageResponse) message; 042 byte[] bytes1 = getBytes(imageResponse.getImage1()); 043 byte[] bytes2 = getBytes(imageResponse.getImage2()); 044 int capacity = bytes1.length + bytes2.length + 8; 045 IoBuffer buffer = IoBuffer.allocate(capacity, false); 046 buffer.putInt(bytes1.length); 047 buffer.put(bytes1); 048 buffer.putInt(bytes2.length); 049 buffer.put(bytes2); 050 buffer.flip(); 051 out.write(buffer); 052 } 053 054 private byte[] getBytes(BufferedImage image) throws IOException { 055 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 056 ImageIO.write(image, "PNG", baos); 057 return baos.toByteArray(); 058 } 059}