чтение и изменение изображений попиксельно на движке приложений Google с Java, почти там - PullRequest
0 голосов
/ 09 октября 2011

это мой первый раз здесь.Надеюсь, что кто-то может дать нам подсказку!

Мы застряли при преобразовании изображений в Google App Engine с помощью Java.Мы в основном хотим добиться следующего:

1) Создать QRCode с помощью Google Chartapi - ГОТОВО 2) Используйте urlfetch, чтобы получить только что сгенерированный qrcode, и используйте pngw / pngr (библиотека изображений для appengine), чтобы прочитать и изменитьпикселей на изображении - ВЫПОЛНЕНО

Теперь мы понятия не имеем, как:

3) сохранить измененное изображение в хранилище больших двоичных объектов, чтобы затем можно было отображать его на экране с помощью API-интерфейса blobstore.* мы использовали библиотеку локально, а локальное сохранение C: \ test.png работает просто отлично.

Код приведен ниже: * Мы использовали библиотеку pngr, которая использует InputStream для PngReader вместо File.Работает App Engine для чтения и изменения попиксельных данных из PNG.http://github.com/jakeri/pngj-for-Google-App-Engine


package com.qrcode.server;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vobject.appengine.java.io.InputStream;

import ar.com.hjg.pngj.ImageLine;
import ar.com.hjg.pngj.PngReader;
import ar.com.hjg.pngj.PngWriter;

public class QrTest extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
        doPost(request, response);


    }
    protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

         try {
            URL url = new URL("http://chart.apis.google.com/chart?
cht=qr&chs=400x400&chl=http://google.com&chld=L%7C0");
            PngReader pngr;
            pngr = new PngReader(url.openStream());
            PngWriter pngw = new PngWriter("Name", pngr.imgInfo);
            pngw.setOverrideFile(true);  // allows to override writen file if
it already exits
            //pngw.prepare(pngr); // not necesary; but this can copy some
informational chunks from original
            int channels = pngr.imgInfo.channels;
            if(channels<3) throw new RuntimeException("Only for truecolour
images");
            for (int row = 0; row < pngr.imgInfo.rows; row++) {
                ImageLine l1 = pngr.readRow(row);
                for(int j=0;j<pngr.imgInfo.cols;j++){
                    String color_filter = Long.toHexString(l1.getPixelRGB8(j));
                    if (color_filter.equals("0")){

                    // CHANGE THE COLOR FOR EACH PIXEL (ROW X COLUMN)
                         l1.scanline[j*channels]= 250;
                    //SHOW THE HEX COLOR FOR EACH PIXEL OF THE IMAGE
                    String out = row +" x " + j +"    -    "      +
Long.toHexString(l1.getPixelRGB8(j));
                    response.getWriter().println(out);
                    //SET THE NEW COLOR FOR EACH COLUMN IN
                    }else{
                        String out = " ==== NOT BLACK ===";
                        out ="\n"+ row +" x " + j +"    -    "      +
Long.toHexString(l1.getPixelRGB8(j));
                        response.getWriter().println(out);
                    }
                }
                //pngw.writeRow(l1);

            }
            pngr.end();
            pngw.end();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Ответы [ 2 ]

1 голос
/ 12 октября 2011

Спасибо за вашу помощь. Вот мое решение: Некоторые полезные ссылки: BlobStore и Получение изображения из BlobKey

    @Override
public String createImage(String origFilename) {

    BlobKey blobKey = null;
    String modifiedURL=null;
    try {
          // Get a file service
          FileService fileService = FileServiceFactory.getFileService();

          // Create a new Blob file with mime-type "image/png"
          AppEngineFile file1 = fileService.createNewBlobFile("image/png");


          boolean lock = true;// This time lock because we intend to finalize

        // Open a channel to write to it
          FileWriteChannel writeChannel = fileService.openWriteChannel(file1, lock);
          OutputStream os = Channels.newOutputStream(writeChannel);

         //Fetching image from URL

          URL url = new URL(escapeHTML(origFilename));      //escape Special Characters     
          PngReader pngr     = new PngReader(url.openStream());

          //Create PngWriter to write to Output Stream
          PngWriter pngw = new PngWriter(os, pngr.imgInfo);

          //Modify the image

            int channels = pngr.imgInfo.channels;

            if(channels<3) throw new RuntimeException("Only for truecolour images");
            for (int row = 0; row < pngr.imgInfo.rows; row++) {
                ImageLine l1 = pngr.readRow(row);
                for(int j=0;j<pngr.imgInfo.cols;j++)
                    l1.scanline[j*channels]=250; // Change the color of the pixel
                pngw.writeRow(l1); //write rows
            }


            // Now finalize
            pngr.end();
            pngw.end();
            os.close(); // close the output stream  

            writeChannel.closeFinally();


            //Get the BlobKey
           blobKey= fileService.getBlobKey(file1);

           /*Using ImageService to retrieve Modified Image URL
           http://code.google.com/appengine/docs/java/images/overview.html
           */
           ImagesService imagesService = ImagesServiceFactory.getImagesService();
           modifiedURL= imagesService.getServingUrl(blobKey);





    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return  modifiedURL;

}

//This is the function to escape special characters
 public static final String escapeHTML(String s) {
     StringBuffer sb = new StringBuffer();
     int n = s.length();
     for (int i = 0; i < n; i++) {
       char c = s.charAt(i);
       switch (c) {
       case '|':
         sb.append("%7C");
         break;
       case ' ':
         sb.append("%20");
         break;

       default:
         sb.append(c);
         break;
       }
     }
     return sb.toString();
   }
1 голос
/ 09 октября 2011

Учитывая эту часть документации , этот код должен помочь вам начать:

FileService fileService = FileServiceFactory.getFileService();

// Create a new Blob file with mime-type "image/png"
AppEngineFile file = fileService.createNewBlobFile("image/png");

// Open a channel to write to it
boolean lock = false;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
OutputStream os = Channels.newOutputSTream(writeChannel);
// TODO :  wrap the os OutputStream into a PngWriter and write the image
out.close();
writeChannel.closeFinally();

// ...

// Now read from the file using the Blobstore API
BlobKey blobKey = fileService.getBlobKey(file);
// TODO serve the blob using the blob key.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...