Java读取图片时抛Unable to render RenderedOp for this operation

2024-06-16 13:48

本文主要是介绍Java读取图片时抛Unable to render RenderedOp for this operation,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

后台http接口读取图片的代码如下,使用的是JAI方式:

byte[] buf = IOUtils.toByteArray(req.getInputStream());PlanarImage image = null;
ByteArraySeekableStream stream = new ByteArraySeekableStream(buf);
image = JAI.create("stream", stream);

然后在image.getWidth()的时候抛出了如下异常:

Error: IOException occurs when search for propriate codecs.
Occurs in: com.sun.media.jai.codec.ImageCodec
java.io.EOFExceptionat com.sun.media.jai.codec.SeekableStream.readFully(SeekableStream.java:320)at com.sun.media.jai.codec.SeekableStream.readFully(SeekableStream.java:297)at com.sun.media.jai.codec.ImageCodec.getDecoderNames(ImageCodec.java:267)at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:72)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:606)at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)at javax.media.jai.RenderedOp.getWidth(RenderedOp.java:2179)at com.soso.zhishi.proc.RatioCropProc.proc(RatioCropProc.java:32)at com.soso.zhishi.ImageFactory.ratioCropAndEncode(ImageFactory.java:117)at com.soso.zhishi.servlet.UploadFixedPicServlet.doPost(UploadFixedPicServlet.java:89)at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1749)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1708)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)at java.lang.Thread.run(Thread.java:745)
java.lang.RuntimeException: - Unable to render RenderedOp for this operation.at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:827)at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)at javax.media.jai.RenderedOp.getWidth(RenderedOp.java:2179)at com.soso.zhishi.proc.RatioCropProc.proc(RatioCropProc.java:32)at com.soso.zhishi.ImageFactory.ratioCropAndEncode(ImageFactory.java:117)at com.soso.zhishi.servlet.UploadFixedPicServlet.doPost(UploadFixedPicServlet.java:89)at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1749)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1708)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)at java.lang.Thread.run(Thread.java:745)

其实详细的异常信息应该是如下:

Error: Cannot decode the image for the type :
Occurs in: com.sun.media.jai.opimage.CodecRIFUtil
java.io.IOException: Premature end of input fileat com.sun.media.jai.codecimpl.CodecUtils.toIOException(CodecUtils.java:76)at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:48)at com.sun.media.jai.opimage.CodecRIFUtil.create(CodecRIFUtil.java:88)at com.sun.media.jai.opimage.JPEGRIF.create(JPEGRIF.java:43)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:102)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)at javax.media.jai.RenderedOp.getHeight(RenderedOp.java:2188)at TestMongodbImage.testImage(TestMongodbImage.java:99)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)at org.junit.runners.ParentRunner.run(ParentRunner.java:363)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)at org.junit.runner.JUnitCore.run(JUnitCore.java:137)at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: com.sun.image.codec.jpeg.TruncatedFileException: Premature end of input fileat sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(JPEGImageDecoderImpl.java:213)at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:110)at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:46)... 56 more
Error: IOException occurs when decode the image.
Occurs in: com.sun.media.jai.opimage.StreamRIF
java.io.IOExceptionat com.sun.media.jai.codecimpl.CodecUtils.toIOException(CodecUtils.java:76)at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:48)at com.sun.media.jai.codec.ImageDecoderImpl.decodeAsRenderedImage(ImageDecoderImpl.java:140)at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:135)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)at javax.media.jai.RenderedOp.getHeight(RenderedOp.java:2188)at TestMongodbImage.testImage(TestMongodbImage.java:99)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)at org.junit.runners.ParentRunner.run(ParentRunner.java:363)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)at org.junit.runner.JUnitCore.run(JUnitCore.java:137)at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)Caused by: com.sun.media.jai.codecimpl.util.ImagingExceptionat com.sun.media.jai.codecimpl.ImagingListenerProxy.errorOccurred(ImagingListenerProxy.java:63)at com.sun.media.jai.codecimpl.JPEGImage.sendExceptionToListener(JPEGImageDecoder.java:172)at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:113)at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:46)... 47 more
Caused by: com.sun.media.jai.codecimpl.util.ImagingException: Unable to process image stream, incorrect format.... 50 more
Caused by: com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(JPEGImageDecoderImpl.java:213)at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:110)... 48 morejava.lang.RuntimeException: - Unable to render RenderedOp for this operation.at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:827)at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)at javax.media.jai.RenderedOp.getHeight(RenderedOp.java:2188)at TestMongodbImage.testImage(TestMongodbImage.java:99)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)at org.junit.runners.ParentRunner.run(ParentRunner.java:363)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)at org.junit.runner.JUnitCore.run(JUnitCore.java:137)at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:497)at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)INFO 2017-07-17 15:40:08 org.springframework.context.support.GenericApplicationContext Closing org.springframework.context.support.GenericApplicationContext@18d30f7: startup date [Mon Jul 17 15:40:07 CST 2017]; root of context hierarchy 
Corrupt JPEG data: premature end of data segment

比较关键的一句话是:

 Not a JPEG file: starts with 0xff 0xd9

看起来服务接口读取图片的时候认为图片格式不是标准JPEG格式的,所以我在调用上述接口上传图片的之前,先试图对图片进行格式转换,我的上传代码是python的,所以先用了如下代码

from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
im = Image.open(waterImage)
im.save(waterImage)

一开始这样做,有部分图片可以成功上传,但是后来发现仍然有很大一部分图片上传失败

发现失败的图片mode类型有CMYK和RGBA以及RGB

于是,我试图将这三种格式都转换成RGB格式

我在网上查了很多资料试图对格式进行转换,最终发现一种可行的转换算法如下,需要对不同的模式采用不同的转换算法:

def parseImgMode(source, dest):	#source是原图地址,dest是目标图地址sourceimg = Image.open(source)print sourceimg.modesize = sourceimg.sizewidth = size[0]height = size[1]destimg = Image.new('RGB', size, (255,255,255))if sourceimg.mode == 'CMYK':for i in range(width):for j in range(height):px = sourceimg.getpixel((i,j))c = px[0] / 255.0m = px[1] / 255.0y = px[2] / 255.0k = px[3] / 255.0nc = (c*(1-k)+k)nm = (m*(1-k)+k)ny = (y*(1-k)+k)r = (int)((1-nc)*255)g = (int)((1-nm)*255)b = (int)((1-ny)*255)destimg.putpixel((i,j), (r,g,b))destimg.save(dest, 'jpeg', quality=100)return destelif sourceimg.mode == 'RGBA':for i in range(width):for j in range(height):px = sourceimg.getpixel((i,j))r = px[0] / 255.0g = px[1] / 255.0b = px[2] / 255.0a = px[3] / 255.0bgcolor = 1r = (int)((bgcolor*(1-a) + r*a)*255)g = (int)((bgcolor*(1-a) + g*a)*255)b = (int)((bgcolor*(1-a) + b*a)*255)destimg.putpixel((i,j), (r,g,b))destimg.save(dest, 'jpeg', quality=100)return destelif sourceimg.mode == 'RGB':img = cv2.imread(source, cv2.IMREAD_COLOR)cv2.imwrite(dest, img)return dest

一开始网上找的CMYK转RGB格式的算法虽然转换后都能上传,但是发现颜色会失真,最终发现上面这种转换算法不会丢失颜色信息

RGBA转RGB的算法上述方式可行,而且下面的代码经测试也可以实现格式转换:

sourceimg = Image.open(source)
destimg = Image.new('RGB', sourceimg.size, (255,255,255))
destimg.paste(sourceimg)
destimg.save(dest, 'jpeg', quality=100)
return dest


但是原图本身就是RGB的情况下,服务接口仍然不识别,但是我用了下面这个地址将图片转换后,上传就成功了:

http://www.jinaconvert.com/cn/convert-to-jpg.php

转换后的图片也是RGB,为什么老的RGB不行,转换后的RGB就可以呢?而且奇怪的是,我对老的图片getpixel得到的值全都是(0,0,0)

这个我就搞不明白为什么了,难道要将RGB转成RGB?所以查了很多资料,尝试了很多图片处理的模块,最终发现opencv可以正确处理

代码如下:

img = cv2.imread(source, cv2.IMREAD_COLOR)
cv2.imwrite(dest, img)
return dest

cv2.IMREAD_COLOR = 1

表示读取的时候要处理颜色,如果这个参数给0,那么处理后的图片没有颜色,这里还可以设置其他的模式


后来我发现,这段代码不仅可以处理mode=RGB情况,其他的都能处理,所以我索性没有区分模式,所有的上传失败的都用如下代码统一处理一次再上传:

img = cv2.imread(source, cv2.IMREAD_COLOR)
cv2.imwrite(dest, img)
return dest










这篇关于Java读取图片时抛Unable to render RenderedOp for this operation的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1066619

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听