我有一个MVC应用程序,您可以上传图片并将其调整为最大值。 50KB。 我在while循环中调整大小,但问题是当我减小文件大小增加的图片的宽度和高度时。在某一点上,尺寸变小但是以质量为代价
.content{
width:80%;
height:300px;
margin:10px auto;
background-color:gold;
text-align:center;
}
要调整大小的代码:
Request.InputStream.Position = 0;
string Data = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
var Base64 = Data.Split(',')[1];
var BitmapBytes = Convert.FromBase64String(Base64);
var Bmp = new Bitmap(new MemoryStream(BitmapBytes));
while (BitmapBytes.Length > 51200)
{
int Schritte = 20; //I tested here also with 300
int maxWidth = Bmp.Width;
maxWidth = maxWidth - Schritte;
int maxHeight = Bmp.Height;
maxHeight = maxHeight - Schritte;
Bmp = ScaleImage(Bmp, maxWidth, maxHeight);
var base64 = ReturnImageAsBase64(Bmp);
BitmapBytes = Convert.FromBase64String(base64);
}
我从66964字节的大小开始。在循环中第一次转弯之后它的85151字节,这虽然宽度减少了300像素,高度减少了420像素。
答案 0 :(得分:0)
从我之前的评论:
我想说这是你的Pixelformat问题。如果您有一个带有1bpp(黑色或白色)的Bitmap并将其绘制到ScaleImage中的newImage,则使用默认的Pixelformat创建newImage,这可能与Colors一起使用,因此最终得到24bpp,这会导致更高的内存大小
尝试更改:
import Tkinter as tk
import Queue
class MainWindow(tk.Frame):
""" This is the GUI
It starts threads and updates the GUI
this is needed as tkinter GUI updates inside the Main Thread
"""
def __init__(self, *args, **kwargs):
# Here some initial action takes place
# ...
self.queue = Queue()
self.start_threads()
self.__running = True
self.update_gui()
def start_threads(self):
""" Here we start the threads
for ease of reading only one right now
thread_handler_class is a class performing
tasks and appending results to a queue
"""
thread = thread_handler_class(self.queue)
def update_gui(self):
""" Update the UI with Information from the queue """
if not self.queue.empty():
# we need to check for emptiness first
# otherwise we get exceptions if empty
while self.queue.qsize() > 0:
# handle the data
# self.queue.get() automatically reduces
# qsize return value next round so if no
# new elements are added to the queue,
# it will go to zero
data = self.queue.get()
# do stuff here
# ...
# Set up the cyclic task
if self.__running:
self.after(100, self.update_gui)
# if neccessary we can also restart the threads
# if they have a determined runtime
# self.after(100, self.start_threads)
if __name__ == "__main__":
APP = MainWindow()
APP.mainloop()
到
Bitmap newImage = new Bitmap(newWidth, newHeight);
编辑:由于使用索引的PixelFormats似乎无法从中创建图形对象,因此似乎没有简单的解决方案。
解释图像尺寸较大的原因:
原始图片: 颜色查找表:
Bitmap newImage = new Bitmap(newWidth, newHeight, image.PixelFormat);
这里有16个像素,16个像素,12个字节用于查找表(索引号为1个字节,每个颜色为RGB通道为3个字节) 因此,图像的总大小为28字节
在newImage中没有查找表,因此每个Pixel都有完整的RGB信息:
1 = Red = 255, 0,0
2 = Black = 0, 0,0
3 = Green = 0,255,0
...
Column
Row 1 2 3 4
1 1 1 1 1
2 1 1 1 1
3 2 2 2 2
4 3 3 3 3
因此newImage的大小为3 * 16 = 48 Bytes