2

我正在使用 GAE[JAVA] 进行一些图像处理。GAE不允许将文件写入磁盘,所以我希望我的App允许输入一个URL,然后我想检查这个指定的URL是否代表图像,如果是,我想获取它的高度和宽度。

有没有人提供一些解决方案来告诉我如何实现这个?

4

2 回答 2

5

您可以使用 GAE Image API。解决您的问题的简单示例是:

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        final InputStream inputStream = url.openStream();
        int read;
        while ((read = inputStream.read()) != -1) {
            baos.write(read);
        }

        final Image image = ImagesServiceFactory.makeImage(baos.toByteArray());

        resp.getWriter().println("image width: " + image.getWidth());
        resp.getWriter().println("image height: " + image.getHeight());
    } catch (final IOException e) {
        resp.getWriter().println("image doesn't exists!");
    } catch (final IllegalArgumentException e) {
        resp.getWriter().println("invalid image!");
    }

完成 Servlet 以执行此操作:

package foo.bar;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

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

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;

@SuppressWarnings("serial")
public class MyFirstWebAppServlet extends HttpServlet {
    @Override
    public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        URL url;
        if ("exists".equals(req.getParameter("image"))) {
            url = new URL("https://www.google.com/logos/classicplus.png");
        } else if ("notImage".equals(req.getParameter("image"))) {
            url = new URL("http://www.google.com");
        } else {
            url = new URL("http://foo.bar/image.png");
        }

        resp.setContentType("text/plain");
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            final InputStream inputStream = url.openStream();
            int read;
            while ((read = inputStream.read()) != -1) {
                baos.write(read);
            }

            final Image image = ImagesServiceFactory.makeImage(baos.toByteArray());

            resp.getWriter().println("image width: " + image.getWidth());
            resp.getWriter().println("image height: " + image.getHeight());
        } catch (final IOException e) {
            resp.getWriter().println("image doesn't exists!");
        } catch (final IllegalArgumentException e) {
            resp.getWriter().println("invalid image!");
        }

    }
}
于 2012-07-01T10:27:22.290 回答
-2

也许这种方式很奇怪,但我认为你可以使用 javascript

var img=new Image();
img.src="http://www.google.com.hk/images/nav_logo107.png";
img.height;
img.width;

在此处输入图像描述

如果图像没有退出,则会抛出 404(未找到)问题。

于 2012-07-01T09:55:30.857 回答